code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; /** * A sample enumerated type we use for testing. * * @author Kevin Bourrillion */ @GwtCompatible public enum AnEnum { A, B, C, D, E, F }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Map; /** * Creates maps, containing sample elements, to be tested. * * @author George van den Driessche */ @GwtCompatible public interface TestMapGenerator<K, V> extends TestContainerGenerator<Map<K, V>, Map.Entry<K, V>> { K[] createKeyArray(int length); V[] createValueArray(int length); }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Colliders; import java.util.List; /** * A generator using sample elements whose hash codes all collide badly. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class TestCollidingSetGenerator implements TestSetGenerator<Object> { @Override public SampleElements<Object> samples() { return new Colliders(); } @Override public Object[] createArray(int length) { return new Object[length]; } /** Returns the original element list, unchanged. */ @Override public List<Object> order(List<Object> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionSize; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Generator for collection of a particular size. * * @author George van den Driessche */ @GwtCompatible public final class OneSizeGenerator<T, E> implements OneSizeTestContainerGenerator<T, E> { private final TestContainerGenerator<T, E> generator; private final CollectionSize collectionSize; public OneSizeGenerator(TestContainerGenerator<T, E> generator, CollectionSize collectionSize) { this.generator = generator; this.collectionSize = collectionSize; } @Override public TestContainerGenerator<T, E> getInnerGenerator() { return generator; } @Override public SampleElements<E> samples() { return generator.samples(); } @Override public T create(Object... elements) { return generator.create(elements); } @Override public E[] createArray(int length) { return generator.createArray(length); } @Override public T createTestSubject() { Collection<E> elements = getSampleElements( getCollectionSize().getNumElements()); return generator.create(elements.toArray()); } @Override public Collection<E> getSampleElements(int howMany) { SampleElements<E> samples = samples(); @SuppressWarnings("unchecked") List<E> allSampleElements = Arrays.asList( samples.e0, samples.e1, samples.e2, samples.e3, samples.e4); return new ArrayList<E>(allSampleElements.subList(0, howMany)); } @Override public CollectionSize getCollectionSize() { return collectionSize; } @Override public Iterable<E> order(List<E> insertionOrder) { return generator.order(insertionOrder); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * This abstract base class for testers allows the framework to inject needed * information after JUnit constructs the instances. * * <p>This class is emulated in GWT. * * @param <G> the type of the test generator required by this tester. An * instance of G should somehow provide an instance of the class under test, * plus any other information required to parameterize the test. * * @author George van den Driessche */ @GwtCompatible public class AbstractTester<G> extends TestCase { private G subjectGenerator; private String suiteName; private Runnable setUp; private Runnable tearDown; // public so that it can be referenced in generated GWT tests. @Override public void setUp() throws Exception { if (setUp != null) { setUp.run(); } } // public so that it can be referenced in generated GWT tests. @Override public void tearDown() throws Exception { if (tearDown != null) { tearDown.run(); } } // public so that it can be referenced in generated GWT tests. public final void init( G subjectGenerator, String suiteName, Runnable setUp, Runnable tearDown) { this.subjectGenerator = subjectGenerator; this.suiteName = suiteName; this.setUp = setUp; this.tearDown = tearDown; } // public so that it can be referenced in generated GWT tests. public final void init(G subjectGenerator, String suiteName) { init(subjectGenerator, suiteName, null, null); } public G getSubjectGenerator() { return subjectGenerator; } /** Returns the name of the test method invoked by this test instance. */ public final String getTestMethodName() { return super.getName(); } @Override public String getName() { return Platform.format("%s[%s]", super.getName(), suiteName); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.List; import java.util.SortedSet; /** * Create integer sets for testing collections that are sorted by natural * ordering. * * @author Chris Povirk * @author Jared Levy */ @GwtCompatible public abstract class TestIntegerSortedSetGenerator extends TestIntegerSetGenerator { @Override protected abstract SortedSet<Integer> create(Integer[] elements); /** Sorts the elements by their natural ordering. */ @Override public List<Integer> order(List<Integer> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; import com.google.common.collect.testing.DerivedCollectionGenerators.SortedSetSubsetTestSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.testers.SortedSetNavigationTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a SortedSet implementation. */ public class SortedSetTestSuiteBuilder<E> extends SetTestSuiteBuilder<E> { public static <E> SortedSetTestSuiteBuilder<E> using( TestSortedSetGenerator<E> generator) { SortedSetTestSuiteBuilder<E> builder = new SortedSetTestSuiteBuilder<E>(); builder.usingGenerator(generator); return builder; } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(SortedSetNavigationTester.class); return testers; } @Override public TestSuite createTestSuite() { if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) { List<Feature<?>> features = Helpers.copyToList(getFeatures()); features.add(CollectionFeature.KNOWN_ORDER); withFeatures(features); } return super.createTestSuite(); } @Override protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder); if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) { derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE)); derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND)); derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE)); } return derivedSuites; } /** * Creates a suite whose set has some elements filtered out of view. * * <p>Because the set may be ascending or descending, this test must derive * the relative order of these extreme values rather than relying on their * regular sort ordering. */ final TestSuite createSubsetSuite(final FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder, final Bound from, final Bound to) { final TestSortedSetGenerator<E> delegate = (TestSortedSetGenerator<E>) parentBuilder.getSubjectGenerator().getInnerGenerator(); List<Feature<?>> features = new ArrayList<Feature<?>>(); features.addAll(parentBuilder.getFeatures()); features.remove(CollectionFeature.ALLOWS_NULL_VALUES); features.add(CollectionFeature.SUBSET_VIEW); return newBuilderUsing(delegate, to, from) .named(parentBuilder.getName() + " subSet " + from + "-" + to) .withFeatures(features) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } /** Like using() but overrideable by NavigableSetTestSuiteBuilder. */ SortedSetTestSuiteBuilder<E> newBuilderUsing( TestSortedSetGenerator<E> delegate, Bound to, Bound from) { return using(new SortedSetSubsetTestSetGenerator<E>(delegate, to, from)); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; /** * An unhashable object to be used in testing as values in our collections. * * @author Regina O'Dell */ @GwtCompatible public class UnhashableObject implements Comparable<UnhashableObject> { private final int value; public UnhashableObject(int value) { this.value = value; } @Override public boolean equals(Object object) { if (object instanceof UnhashableObject) { UnhashableObject that = (UnhashableObject) object; return this.value == that.value; } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } // needed because otherwise Object.toString() calls hashCode() @Override public String toString() { return "DontHashMe" + value; } @Override public int compareTo(UnhashableObject o) { return (this.value < o.value) ? -1 : (this.value > o.value) ? 1 : 0; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import junit.framework.Test; import junit.framework.TestSuite; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; /** * Generates a test suite covering the {@link Map} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Kevin Bourrillion */ public class TestsForMapsInJavaUtil { public static Test suite() { return new TestsForMapsInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite("java.util Maps"); suite.addTest(testsForEmptyMap()); suite.addTest(testsForSingletonMap()); suite.addTest(testsForHashMap()); suite.addTest(testsForLinkedHashMap()); suite.addTest(testsForTreeMapNatural()); suite.addTest(testsForTreeMapWithComparator()); suite.addTest(testsForEnumMap()); suite.addTest(testsForConcurrentHashMap()); suite.addTest(testsForConcurrentSkipListMapNatural()); suite.addTest(testsForConcurrentSkipListMapWithComparator()); return suite; } protected Collection<Method> suppressForEmptyMap() { return Collections.emptySet(); } protected Collection<Method> suppressForSingletonMap() { return Collections.emptySet(); } protected Collection<Method> suppressForHashMap() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedHashMap() { return Collections.emptySet(); } protected Collection<Method> suppressForTreeMapNatural() { return Collections.emptySet(); } protected Collection<Method> suppressForTreeMapWithComparator() { return Collections.emptySet(); } protected Collection<Method> suppressForEnumMap() { return Collections.emptySet(); } protected Collection<Method> suppressForConcurrentHashMap() { return Collections.emptySet(); } protected Collection<Method> suppressForConcurrentSkipListMap() { return Collections.emptySet(); } public Test testsForEmptyMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return Collections.emptyMap(); } }) .named("emptyMap") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionSize.ZERO) .suppressing(suppressForEmptyMap()) .createTestSuite(); } public Test testsForSingletonMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return Collections.singletonMap( entries[0].getKey(), entries[0].getValue()); } }) .named("singletonMap") .withFeatures( MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.SERIALIZABLE, CollectionSize.ONE) .suppressing(suppressForSingletonMap()) .createTestSuite(); } public Test testsForHashMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return toHashMap(entries); } }) .named("HashMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForHashMap()) .createTestSuite(); } public Test testsForLinkedHashMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return populate(new LinkedHashMap<String, String>(), entries); } }) .named("LinkedHashMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForLinkedHashMap()) .createTestSuite(); } public Test testsForTreeMapNatural() { return NavigableMapTestSuiteBuilder .using(new TestStringSortedMapGenerator() { @Override protected SortedMap<String, String> create( Entry<String, String>[] entries) { /* * TODO(cpovirk): it would be nice to create an input Map and use * the copy constructor here and in the other tests */ return populate(new TreeMap<String, String>(), entries); } }) .named("TreeMap, natural") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForTreeMapNatural()) .createTestSuite(); } public Test testsForTreeMapWithComparator() { return NavigableMapTestSuiteBuilder .using(new TestStringSortedMapGenerator() { @Override protected SortedMap<String, String> create( Entry<String, String>[] entries) { return populate(new TreeMap<String, String>( arbitraryNullFriendlyComparator()), entries); } }) .named("TreeMap, with comparator") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForTreeMapWithComparator()) .createTestSuite(); } public Test testsForEnumMap() { return MapTestSuiteBuilder .using(new TestEnumMapGenerator() { @Override protected Map<AnEnum, String> create( Entry<AnEnum, String>[] entries) { return populate( new EnumMap<AnEnum, String>(AnEnum.class), entries); } }) .named("EnumMap") .withFeatures( MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, MapFeature.RESTRICTS_KEYS, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForEnumMap()) .createTestSuite(); } public Test testsForConcurrentHashMap() { return MapTestSuiteBuilder .using(new TestStringMapGenerator() { @Override protected Map<String, String> create( Entry<String, String>[] entries) { return populate(new ConcurrentHashMap<String, String>(), entries); } }) .named("ConcurrentHashMap") .withFeatures( MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForConcurrentHashMap()) .createTestSuite(); } public Test testsForConcurrentSkipListMapNatural() { return NavigableMapTestSuiteBuilder .using(new TestStringSortedMapGenerator() { @Override protected SortedMap<String, String> create( Entry<String, String>[] entries) { return populate(new ConcurrentSkipListMap<String, String>(), entries); } }) .named("ConcurrentSkipListMap, natural") .withFeatures( MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForConcurrentSkipListMap()) .createTestSuite(); } public Test testsForConcurrentSkipListMapWithComparator() { return NavigableMapTestSuiteBuilder .using(new TestStringSortedMapGenerator() { @Override protected SortedMap<String, String> create( Entry<String, String>[] entries) { return populate(new ConcurrentSkipListMap<String, String>( arbitraryNullFriendlyComparator()), entries); } }) .named("ConcurrentSkipListMap, with comparator") .withFeatures( MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .suppressing(suppressForConcurrentSkipListMap()) .createTestSuite(); } // TODO: IdentityHashMap, AbstractMap private static Map<String, String> toHashMap( Entry<String, String>[] entries) { return populate(new HashMap<String, String>(), entries); } // TODO: call conversion constructors or factory methods instead of using // populate() on an empty map private static <T, M extends Map<T, String>> M populate( M map, Entry<T, String>[] entries) { for (Entry<T, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } static <T> Comparator<T> arbitraryNullFriendlyComparator() { return new NullFriendlyComparator<T>(); } private static final class NullFriendlyComparator<T> implements Comparator<T>, Serializable { @Override public int compare(T left, T right) { return String.valueOf(left).compareTo(String.valueOf(right)); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Enums; import java.util.Collections; import java.util.List; import java.util.Set; /** * An abstract TestSetGenerator for generating sets containing enum values. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class TestEnumSetGenerator implements TestSetGenerator<AnEnum> { @Override public SampleElements<AnEnum> samples() { return new Enums(); } @Override public Set<AnEnum> create(Object... elements) { AnEnum[] array = new AnEnum[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (AnEnum) e; } return create(array); } protected abstract Set<AnEnum> create(AnEnum[] elements); @Override public AnEnum[] createArray(int length) { return new AnEnum[length]; } /** * Sorts the enums according to their natural ordering. */ @Override public List<AnEnum> order(List<AnEnum> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import junit.framework.Assert; import junit.framework.AssertionFailedError; /** * Tests serialization and deserialization of an object, optionally asserting * that the resulting object is equal to the original. * * <p><b>GWT warning:</b> Under GWT, both methods simply returns their input, * as proper GWT serialization tests require more setup. This no-op behavior * allows test authors to intersperse {@code SerializableTester} calls with * other, GWT-compatible tests. * * * @author Mike Bostock * @since 10.0 */ @Beta @GwtCompatible // but no-op! public final class SerializableTester { private SerializableTester() {} /** * Serializes and deserializes the specified object. * * <p><b>GWT warning:</b> Under GWT, this method simply returns its input, as * proper GWT serialization tests require more setup. This no-op behavior * allows test authors to intersperse {@code SerializableTester} calls with * other, GWT-compatible tests. * * <p>Note that the specified object may not be known by the compiler to be a * {@link java.io.Serializable} instance, and is thus declared an * {@code Object}. For example, it might be declared as a {@code List}. * * @return the re-serialized object * @throws RuntimeException if the specified object was not successfully * serialized or deserialized */ @SuppressWarnings("unchecked") public static <T> T reserialize(T object) { return Platform.reserialize(object); } /** * Serializes and deserializes the specified object and verifies that the * re-serialized object is equal to the provided object, that the hashcodes * are identical, and that the class of the re-serialized object is identical * to that of the original. * * <p><b>GWT warning:</b> Under GWT, this method simply returns its input, as * proper GWT serialization tests require more setup. This no-op behavior * allows test authors to intersperse {@code SerializableTester} calls with * other, GWT-compatible tests. * * <p>Note that the specified object may not be known by the compiler to be a * {@link java.io.Serializable} instance, and is thus declared an * {@code Object}. For example, it might be declared as a {@code List}. * * <p>Note also that serialization is not in general required to return an * object that is {@linkplain Object#equals equal} to the original, nor is it * required to return even an object of the same class. For example, if * sublists of {@code MyList} instances were serializable, those sublists * might implement a private {@code MySubList} type but serialize as a plain * {@code MyList} to save space. So long as {@code MyList} has all the public * supertypes of {@code MySubList}, this is safe. For these cases, for which * {@code reserializeAndAssert} is too strict, use {@link #reserialize}. * * @return the re-serialized object * @throws RuntimeException if the specified object was not successfully * serialized or deserialized * @throws AssertionFailedError if the re-serialized object is not equal to * the original object, or if the hashcodes are different. */ public static <T> T reserializeAndAssert(T object) { T copy = reserialize(object); new EqualsTester() .addEqualityGroup(object, copy) .testEquals(); Assert.assertEquals(object.getClass(), copy.getClass()); return copy; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * A {@code TearDownStack} contains a stack of {@link TearDown} instances. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible public class TearDownStack implements TearDownAccepter { public static final Logger logger = Logger.getLogger(TearDownStack.class.getName()); final LinkedList<TearDown> stack = new LinkedList<TearDown>(); private final boolean suppressThrows; public TearDownStack() { this.suppressThrows = false; } public TearDownStack(boolean suppressThrows) { this.suppressThrows = suppressThrows; } @Override public final void addTearDown(TearDown tearDown) { stack.addFirst(checkNotNull(tearDown)); } /** * Causes teardown to execute. */ public final void runTearDown() { List<Throwable> exceptions = new ArrayList<Throwable>(); for (TearDown tearDown : stack) { try { tearDown.tearDown(); } catch (Throwable t) { if (suppressThrows) { TearDownStack.logger.log(Level.INFO, "exception thrown during tearDown: " + t.getMessage(), t); } else { exceptions.add(t); } } } stack.clear(); if ((!suppressThrows) && (exceptions.size() > 0)) { throw ClusterException.create(exceptions); } } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.Beta; import java.lang.ref.WeakReference; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; /** * Testing utilities relating to garbage collection finalization. * * <p>Use this class to test code triggered by <em>finalization</em>, that is, one of the * following actions taken by the java garbage collection system: * * <ul> * <li>invoking the {@code finalize} methods of unreachable objects * <li>clearing weak references to unreachable referents * <li>enqueuing weak references to unreachable referents in their reference queue * </ul> * * <p>This class uses (possibly repeated) invocations of {@link java.lang.System#gc()} to cause * finalization to happen. However, a call to {@code System.gc()} is specified to be no more * than a hint, so this technique may fail at the whim of the JDK implementation, for example if * a user specified the JVM flag {@code -XX:+DisableExplicitGC}. But in practice, it works very * well for ordinary tests. * * <p>Failure of the expected event to occur within an implementation-defined "reasonable" time * period or an interrupt while waiting for the expected event will result in a {@link * RuntimeException}. * * <p>Here's an example that tests a {@code finalize} method: * * <pre> {@code * final CountDownLatch latch = new CountDownLatch(1); * Object x = new MyClass() { * ... * protected void finalize() { latch.countDown(); ... } * }; * x = null; // Hint to the JIT that x is stack-unreachable * GcFinalization.await(latch);}</pre> * * <p>Here's an example that uses a user-defined finalization predicate: * * <pre> {@code * final WeakHashMap<Object, Object> map = new WeakHashMap<Object, Object>(); * map.put(new Object(), Boolean.TRUE); * GcFinalization.awaitDone(new FinalizationPredicate() { * public boolean isDone() { * return map.isEmpty(); * } * });}</pre> * * <p>Even if your non-test code does not use finalization, you can * use this class to test for leaks, by ensuring that objects are no * longer strongly referenced: * * <pre> {@code * // Helper function keeps victim stack-unreachable. * private WeakReference<Foo> fooWeakRef() { * Foo x = ....; * WeakReference<Foo> weakRef = new WeakReference<Foo>(x); * // ... use x ... * x = null; // Hint to the JIT that x is stack-unreachable * return weakRef; * } * public void testFooLeak() { * GcFinalization.awaitClear(fooWeakRef()); * }}</pre> * * <p>This class cannot currently be used to test soft references, since this class does not try to * create the memory pressure required to cause soft references to be cleared. * * <p>This class only provides testing utilities. It is not designed for direct use in production * or for benchmarking. * * @author mike nonemacher * @author Martin Buchholz * @since 11.0 */ @Beta public final class GcFinalization { private GcFinalization() {} /** * 10 seconds ought to be long enough for any object to be GC'ed and finalized. Unless we have a * gigantic heap, in which case we scale by heap size. */ private static long timeoutSeconds() { // This class can make no hard guarantees. The methods in this class are inherently flaky, but // we try hard to make them robust in practice. We could additionally try to add in a system // load timeout multiplier. Or we could try to use a CPU time bound instead of wall clock time // bound. But these ideas are harder to implement. We do not try to detect or handle a // user-specified -XX:+DisableExplicitGC. // // TODO(user): Consider using // java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage() // // TODO(user): Consider scaling by number of mutator threads, // e.g. using Thread#activeCount() return Math.max(10L, Runtime.getRuntime().totalMemory() / (32L * 1024L * 1024L)); } /** * Waits until the given future {@linkplain Future#isDone is done}, invoking the garbage * collector as necessary to try to ensure that this will happen. * * @throws RuntimeException if timed out or interrupted while waiting */ public static void awaitDone(Future<?> future) { if (future.isDone()) { return; } final long timeoutSeconds = timeoutSeconds(); final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds); do { System.runFinalization(); if (future.isDone()) { return; } System.gc(); try { future.get(1L, SECONDS); return; } catch (CancellationException ok) { return; } catch (ExecutionException ok) { return; } catch (InterruptedException ie) { throw new RuntimeException("Unexpected interrupt while waiting for future", ie); } catch (TimeoutException tryHarder) { /* OK */ } } while (System.nanoTime() - deadline < 0); throw new RuntimeException( String.format("Future not done within %d second timeout", timeoutSeconds)); } /** * Waits until the given latch has {@linkplain CountDownLatch#countDown counted down} to zero, * invoking the garbage collector as necessary to try to ensure that this will happen. * * @throws RuntimeException if timed out or interrupted while waiting */ public static void await(CountDownLatch latch) { if (latch.getCount() == 0) { return; } final long timeoutSeconds = timeoutSeconds(); final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds); do { System.runFinalization(); if (latch.getCount() == 0) { return; } System.gc(); try { if (latch.await(1L, SECONDS)) { return; } } catch (InterruptedException ie) { throw new RuntimeException("Unexpected interrupt while waiting for latch", ie); } } while (System.nanoTime() - deadline < 0); throw new RuntimeException( String.format("Latch failed to count down within %d second timeout", timeoutSeconds)); } /** * Creates a garbage object that counts down the latch in its finalizer. Sequestered into a * separate method to make it somewhat more likely to be unreachable. */ private static void createUnreachableLatchFinalizer(final CountDownLatch latch) { new Object() { @Override protected void finalize() { latch.countDown(); }}; } /** * A predicate that is expected to return true subsequent to <em>finalization</em>, that is, one * of the following actions taken by the garbage collector when performing a full collection in * response to {@link System#gc()}: * * <ul> * <li>invoking the {@code finalize} methods of unreachable objects * <li>clearing weak references to unreachable referents * <li>enqueuing weak references to unreachable referents in their reference queue * </ul> */ public interface FinalizationPredicate { boolean isDone(); } /** * Waits until the given predicate returns true, invoking the garbage collector as necessary to * try to ensure that this will happen. * * @throws RuntimeException if timed out or interrupted while waiting */ public static void awaitDone(FinalizationPredicate predicate) { if (predicate.isDone()) { return; } final long timeoutSeconds = timeoutSeconds(); final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds); do { System.runFinalization(); if (predicate.isDone()) { return; } CountDownLatch done = new CountDownLatch(1); createUnreachableLatchFinalizer(done); await(done); if (predicate.isDone()) { return; } } while (System.nanoTime() - deadline < 0); throw new RuntimeException( String.format("Predicate did not become true within %d second timeout", timeoutSeconds)); } /** * Waits until the given weak reference is cleared, invoking the garbage collector as necessary * to try to ensure that this will happen. * * <p>This is a convenience method, equivalent to: * <pre> {@code * awaitDone(new FinalizationPredicate() { * public boolean isDone() { * return ref.get() == null; * } * });}</pre> * * @throws RuntimeException if timed out or interrupted while waiting */ public static void awaitClear(final WeakReference<?> ref) { awaitDone(new FinalizationPredicate() { public boolean isDone() { return ref.get() == null; } }); } /** * Tries to perform a "full" garbage collection cycle (including processing of weak references * and invocation of finalize methods) and waits for it to complete. Ensures that at least one * weak reference has been cleared and one {@code finalize} method has been run before this * method returns. This method may be useful when testing the garbage collection mechanism * itself, or inhibiting a spontaneous GC initiation in subsequent code. * * <p>In contrast, a plain call to {@link java.lang.System#gc()} does not ensure finalization * processing and may run concurrently, for example, if the JVM flag {@code * -XX:+ExplicitGCInvokesConcurrent} is used. * * <p>Whenever possible, it is preferable to test directly for some observable change resulting * from GC, as with {@link #awaitClear}. Because there are no guarantees for the order of GC * finalization processing, there may still be some unfinished work for the GC to do after this * method returns. * * <p>This method does not create any memory pressure as would be required to cause soft * references to be processed. * * @throws RuntimeException if timed out or interrupted while waiting * @since 12.0 */ public static void awaitFullGc() { final CountDownLatch finalizerRan = new CountDownLatch(1); WeakReference<Object> ref = new WeakReference<Object>( new Object() { @Override protected void finalize() { finalizerRan.countDown(); } }); await(finalizerRan); awaitClear(ref); // Hope to catch some stragglers queued up behind our finalizable object System.runFinalization(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import com.google.common.annotations.Beta; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Handler; import java.util.logging.LogRecord; import javax.annotation.Nullable; /** * Tests may use this to intercept messages that are logged by the code under * test. Example: * <pre> * TestLogHandler handler; * * protected void setUp() throws Exception { * super.setUp(); * handler = new TestLogHandler(); * SomeClass.logger.addHandler(handler); * addTearDown(new TearDown() { * public void tearDown() throws Exception { * SomeClass.logger.removeHandler(handler); * } * }); * } * * public void test() { * SomeClass.foo(); * LogRecord firstRecord = handler.getStoredLogRecords().get(0); * assertEquals("some message", firstRecord.getMessage()); * } * </pre> * * @author Kevin Bourrillion * @since 10.0 */ @Beta public class TestLogHandler extends Handler { /** We will keep a private list of all logged records */ private final List<LogRecord> list = Collections.synchronizedList(new ArrayList<LogRecord>()); /** * Adds the most recently logged record to our list. */ @Override public void publish(@Nullable LogRecord record) { list.add(record); } @Override public void flush() {} @Override public void close() {} public void clear() { list.clear(); } /** * Fetch the list of logged records * @return unmodifiable LogRecord list of all logged records */ public List<LogRecord> getStoredLogRecords() { List<LogRecord> result = new ArrayList<LogRecord>(list); return Collections.unmodifiableList(result); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Equivalence; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.testing.RelationshipTester.RelationshipAssertion; import java.util.List; /** * Tester for {@link Equivalence} relationships between groups of objects. * * <p> * To use, create a new {@link EquivalenceTester} and add equivalence groups * where each group contains objects that are supposed to be equal to each * other. Objects of different groups are expected to be unequal. For example: * * <pre> * {@code * EquivalenceTester.of(someStringEquivalence) * .addEquivalenceGroup("hello", "h" + "ello") * .addEquivalenceGroup("world", "wor" + "ld") * .test(); * } * </pre> * * <p> * Note that testing {@link Object#equals(Object)} is more simply done using * the {@link EqualsTester}. It includes an extra test against an instance of an * arbitrary class without having to explicitly add another equivalence group. * * @author Gregory Kick * @since 10.0 * * TODO(gak): turn this into a test suite so that each test can fail * independently */ @Beta @GwtCompatible public final class EquivalenceTester<T> { private static final int REPETITIONS = 3; private final Equivalence<? super T> equivalence; private final RelationshipTester<T> delegate; private final List<T> items = Lists.newArrayList(); EquivalenceTester(final Equivalence<? super T> equivalence) { this.equivalence = checkNotNull(equivalence); this.delegate = new RelationshipTester<T>(new RelationshipAssertion<T>() { @Override public void assertRelated(T item, T related) { assertTrue("$ITEM must be equivalent to $RELATED", equivalence.equivalent(item, related)); int itemHash = equivalence.hash(item); int relatedHash = equivalence.hash(related); assertEquals("the hash (" + itemHash + ") of $ITEM must be equal to the hash (" + relatedHash + ") of $RELATED", itemHash, relatedHash); } @Override public void assertUnrelated(T item, T unrelated) { assertTrue("$ITEM must be inequivalent to $UNRELATED", !equivalence.equivalent(item, unrelated)); } }); } public static <T> EquivalenceTester<T> of(Equivalence<? super T> equivalence) { return new EquivalenceTester<T>(equivalence); } /** * Adds a group of objects that are supposed to be equivalent to each other * and not equivalent to objects in any other equivalence group added to this * tester. */ public EquivalenceTester<T> addEquivalenceGroup(T first, T... rest) { addEquivalenceGroup(Lists.asList(first, rest)); return this; } public EquivalenceTester<T> addEquivalenceGroup(Iterable<T> group) { delegate.addRelatedGroup(group); items.addAll(ImmutableList.copyOf(group)); return this; } /** Run tests on equivalence methods, throwing a failure on an invalid test */ public EquivalenceTester<T> test() { for (int run = 0; run < REPETITIONS; run++) { testItems(); delegate.test(); } return this; } private void testItems() { for (T item : items) { assertTrue(item + " must be inequivalent to null", !equivalence.equivalent(item, null)); assertTrue("null must be inequivalent to " + item, !equivalence.equivalent(null, item)); assertTrue(item + " must be equivalent to itself", equivalence.equivalent(item, item)); assertEquals("the hash of " + item + " must be consistent", equivalence.hash(item), equivalence.hash(item)); } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * An object that can perform a {@link #tearDown} operation. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible public interface TearDown { /** * Performs a <b>single</b> tear-down operation. See test-libraries-for-java's * {@code com.google.common.testing.junit3.TearDownTestCase} and * {@code com.google.common.testing.junit4.TearDownTestCase} for example. * * <p>A failing {@link TearDown} may or may not fail a tl4j test, depending on * the version of JUnit test case you are running under. To avoid failing in * the face of an exception regardless of JUnit version, implement a {@link * SloppyTearDown} instead. * * <p>tl4j details: For backwards compatibility, {@code * junit3.TearDownTestCase} currently does not fail a test when an exception * is thrown from one of its {@link TearDown} instances, but this is subject to * change. Also, {@code junit4.TearDownTestCase} will. * * @throws Exception for any reason. {@code TearDownTestCase} ensures that * any exception thrown will not interfere with other TearDown * operations. */ void tearDown() throws Exception; }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import junit.framework.AssertionFailedError; import java.util.List; /** * Tests a collection of objects according to the rules specified in a * {@link RelationshipAssertion}. * * @author Gregory Kick */ @GwtCompatible final class RelationshipTester<T> { static class ItemReporter { String reportItem(Item item) { return item.toString(); } } private final List<ImmutableList<T>> groups = Lists.newArrayList(); private final RelationshipAssertion<T> assertion; private final ItemReporter itemReporter; RelationshipTester(RelationshipAssertion<T> assertion, ItemReporter itemReporter) { this.assertion = checkNotNull(assertion); this.itemReporter = checkNotNull(itemReporter); } RelationshipTester(RelationshipAssertion<T> assertion) { this(assertion, new ItemReporter()); } public RelationshipTester<T> addRelatedGroup(Iterable<? extends T> group) { groups.add(ImmutableList.copyOf(group)); return this; } public void test() { for (int groupNumber = 0; groupNumber < groups.size(); groupNumber++) { ImmutableList<T> group = groups.get(groupNumber); for (int itemNumber = 0; itemNumber < group.size(); itemNumber++) { // check related items in same group for (int relatedItemNumber = 0; relatedItemNumber < group.size(); relatedItemNumber++) { if (itemNumber != relatedItemNumber) { assertRelated(groupNumber, itemNumber, relatedItemNumber); } } // check unrelated items in all other groups for (int unrelatedGroupNumber = 0; unrelatedGroupNumber < groups.size(); unrelatedGroupNumber++) { if (groupNumber != unrelatedGroupNumber) { ImmutableList<T> unrelatedGroup = groups.get(unrelatedGroupNumber); for (int unrelatedItemNumber = 0; unrelatedItemNumber < unrelatedGroup.size(); unrelatedItemNumber++) { assertUnrelated(groupNumber, itemNumber, unrelatedGroupNumber, unrelatedItemNumber); } } } } } } private void assertRelated(int groupNumber, int itemNumber, int relatedItemNumber) { ImmutableList<T> group = groups.get(groupNumber); T item = group.get(itemNumber); T related = group.get(relatedItemNumber); try { assertion.assertRelated(item, related); } catch (AssertionFailedError e) { // TODO(gak): special handling for ComparisonFailure? throw new AssertionFailedError(e.getMessage() .replace("$ITEM", itemReporter.reportItem(new Item(item, groupNumber, itemNumber))) .replace("$RELATED", itemReporter.reportItem(new Item(related, groupNumber, relatedItemNumber)))); } } private void assertUnrelated(int groupNumber, int itemNumber, int unrelatedGroupNumber, int unrelatedItemNumber) { T item = groups.get(groupNumber).get(itemNumber); T unrelated = groups.get(unrelatedGroupNumber).get(unrelatedItemNumber); try { assertion.assertUnrelated(item, unrelated); } catch (AssertionFailedError e) { // TODO(gak): special handling for ComparisonFailure? throw new AssertionFailedError(e.getMessage() .replace("$ITEM", itemReporter.reportItem(new Item(item, groupNumber, itemNumber))) .replace("$UNRELATED", itemReporter.reportItem( new Item(unrelated, unrelatedGroupNumber, unrelatedItemNumber)))); } } static final class Item { final Object value; final int groupNumber; final int itemNumber; Item(Object value, int groupNumber, int itemNumber) { this.value = value; this.groupNumber = groupNumber; this.itemNumber = itemNumber; } @Override public String toString() { return new StringBuilder() .append(value) .append(" [group ") .append(groupNumber + 1) .append(", item ") .append(itemNumber + 1) .append(']') .toString(); } } /** * A strategy for testing the relationship between objects. Methods are expected to throw * {@link AssertionFailedError} whenever the relationship is violated. * * <p>As a convenience, any occurrence of {@code $ITEM}, {@code $RELATED} or {@code $UNRELATED} in * the error message will be replaced with a string that combines the {@link Object#toString()}, * item number and group number of the respective item. * */ static abstract class RelationshipAssertion<T> { abstract void assertRelated(T item, T related); abstract void assertUnrelated(T item, T unrelated); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Chris Povirk */ final class Platform { /** * Serializes and deserializes the specified object. */ @SuppressWarnings("unchecked") static <T> T reserialize(T object) { checkNotNull(object); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(object); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bytes.toByteArray())); return (T) in.readObject(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private Platform() {} }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.reflect.AbstractInvocationHandler; import com.google.common.reflect.Reflection; import java.lang.reflect.AccessibleObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * Tester to ensure forwarding wrapper works by delegating calls to the corresponding method * with the same parameters forwarded and return value forwarded back or exception propagated as is. * * <p>For example: <pre> {@code * new ForwardingWrapperTester().testForwarding(Foo.class, new Function<Foo, Foo>() { * public Foo apply(Foo foo) { * return new ForwardingFoo(foo); * } * });}</pre> * * @author Ben Yu * @since 14.0 */ @Beta public final class ForwardingWrapperTester { private boolean testsEquals = false; /** * Asks for {@link Object#equals} and {@link Object#hashCode} to be tested. * That is, forwarding wrappers of equal instances should be equal. */ public ForwardingWrapperTester includingEquals() { this.testsEquals = true; return this; } /** * Tests that the forwarding wrapper returned by {@code wrapperFunction} properly forwards * method calls with parameters passed as is, return value returned as is, and exceptions * propagated as is. */ public <T> void testForwarding( Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) { checkNotNull(wrapperFunction); checkArgument(interfaceType.isInterface(), "%s isn't an interface", interfaceType); Method[] methods = getMostConcreteMethods(interfaceType); AccessibleObject.setAccessible(methods, true); for (Method method : methods) { // The interface could be package-private or private. // filter out equals/hashCode/toString if (method.getName().equals("equals") && method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class) { continue; } if (method.getName().equals("hashCode") && method.getParameterTypes().length == 0) { continue; } if (method.getName().equals("toString") && method.getParameterTypes().length == 0) { continue; } testSuccessfulForwarding(interfaceType, method, wrapperFunction); testExceptionPropagation(interfaceType, method, wrapperFunction); } if (testsEquals) { testEquals(interfaceType, wrapperFunction); } testToString(interfaceType, wrapperFunction); } /** Returns the most concrete public methods from {@code type}. */ private static Method[] getMostConcreteMethods(Class<?> type) { Method[] methods = type.getMethods(); for (int i = 0; i < methods.length; i++) { try { methods[i] = type.getMethod(methods[i].getName(), methods[i].getParameterTypes()); } catch (Exception e) { throw Throwables.propagate(e); } } return methods; } private static <T> void testSuccessfulForwarding( Class<T> interfaceType, Method method, Function<? super T, ? extends T> wrapperFunction) { new InteractionTester<T>(interfaceType, method).testInteraction(wrapperFunction); } private static <T> void testExceptionPropagation( Class<T> interfaceType, Method method, Function<? super T, ? extends T> wrapperFunction) { final RuntimeException exception = new RuntimeException(); T proxy = Reflection.newProxy(interfaceType, new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object p, Method m, Object[] args) throws Throwable { throw exception; } }); T wrapper = wrapperFunction.apply(proxy); try { method.invoke(wrapper, getParameterValues(method)); fail(method + " failed to throw exception as is."); } catch (InvocationTargetException e) { if (exception != e.getCause()) { throw new RuntimeException(e); } } catch (IllegalAccessException e) { throw new AssertionError(e); } } private static <T> void testEquals( Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) { FreshValueGenerator generator = new FreshValueGenerator(); T instance = generator.newProxy(interfaceType); new EqualsTester() .addEqualityGroup(wrapperFunction.apply(instance), wrapperFunction.apply(instance)) .addEqualityGroup(wrapperFunction.apply(generator.newProxy(interfaceType))) // TODO: add an overload to EqualsTester to print custom error message? .testEquals(); } private static <T> void testToString( Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) { T proxy = new FreshValueGenerator().newProxy(interfaceType); assertEquals("toString() isn't properly forwarded", proxy.toString(), wrapperFunction.apply(proxy).toString()); } private static Object[] getParameterValues(Method method) { FreshValueGenerator paramValues = new FreshValueGenerator(); final List<Object> passedArgs = Lists.newArrayList(); for (Class<?> paramType : method.getParameterTypes()) { passedArgs.add(paramValues.generate(paramType)); } return passedArgs.toArray(); } /** Tests a single interaction against a method. */ private static final class InteractionTester<T> extends AbstractInvocationHandler { private final Class<T> interfaceType; private final Method method; private final Object[] passedArgs; private final Object returnValue; private final AtomicInteger called = new AtomicInteger(); InteractionTester(Class<T> interfaceType, Method method) { this.interfaceType = interfaceType; this.method = method; this.passedArgs = getParameterValues(method); this.returnValue = new FreshValueGenerator().generate(method.getReturnType()); } @Override protected Object handleInvocation(Object p, Method calledMethod, Object[] args) throws Throwable { assertEquals(method, calledMethod); assertEquals(method + " invoked more than once.", 0, called.get()); for (int i = 0; i < passedArgs.length; i++) { assertEquals("Parameter #" + i + " of " + method + " not forwarded", passedArgs[i], args[i]); } called.getAndIncrement(); return returnValue; } void testInteraction(Function<? super T, ? extends T> wrapperFunction) { T proxy = Reflection.newProxy(interfaceType, this); T wrapper = wrapperFunction.apply(proxy); boolean isPossibleChainingCall = interfaceType.isAssignableFrom(method.getReturnType()); try { Object actualReturnValue = method.invoke(wrapper, passedArgs); // If we think this might be a 'chaining' call then we allow the return value to either // be the wrapper or the returnValue. if (!isPossibleChainingCall || wrapper != actualReturnValue) { assertEquals("Return value of " + method + " not forwarded", returnValue, actualReturnValue); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw Throwables.propagate(e.getCause()); } assertEquals("Failed to forward to " + method, 1, called.get()); } @Override public String toString() { return "dummy " + interfaceType.getSimpleName(); } } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains testing utilities. * It is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. */ @javax.annotation.ParametersAreNonnullByDefault package com.google.common.testing;
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.not; import static com.google.common.testing.AbstractPackageSanityTests.Chopper.suffix; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.reflect.ClassPath; import com.google.common.testing.NullPointerTester.Visibility; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.junit.Test; import java.io.IOException; import java.io.Serializable; import java.util.LinkedHashSet; import java.util.List; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Automatically runs sanity checks against top level classes in the same package of the test that * extends {@code AbstractPackageSanityTests}. Currently sanity checks include {@link * NullPointerTester}, {@link EqualsTester} and {@link SerializableTester}. For example: <pre> * public class PackageSanityTests extends AbstractPackageSanityTests {} * </pre> * * <p>Note that only top-level classes with either a non-private constructor or a non-private static * factory method to construct instances can have their instance methods checked. For example: <pre> * public class Address { * private final String city; * private final String state; * private final String zipcode; * * public Address(String city, String state, String zipcode) {...} * * {@literal @Override} public boolean equals(Object obj) {...} * {@literal @Override} public int hashCode() {...} * ... * } * </pre> * <p>No cascading checks are performed against the return values of methods unless the method is a * static factory method. Neither are semantics of mutation methods such as {@code * someList.add(obj)} checked. For more detailed discussion of supported and unsupported cases, see * {@link #testEquals}, {@link #testNulls} and {@link #testSerializable}. * * <p>For testing against the returned instances from a static factory class, such as <pre> * interface Book {...} * public class Books { * public static Book hardcover(String title) {...} * public static Book paperback(String title) {...} * } * </pre> * <p>please use {@link ClassSanityTester#forAllPublicStaticMethods}. * * <p>This class incurs IO because it scans the classpath and reads classpath resources. * * @author Ben Yu * @since 14.0 */ @Beta // TODO: Switch to JUnit 4 and use @Parameterized and @BeforeClass public abstract class AbstractPackageSanityTests extends TestCase { /* The names of the expected method that tests null checks. */ private static final ImmutableList<String> NULL_TEST_METHOD_NAMES = ImmutableList.of( "testNulls", "testNull", "testNullPointers", "testNullPointer", "testNullPointerExceptions", "testNullPointerException"); /* The names of the expected method that tests serializable. */ private static final ImmutableList<String> SERIALIZABLE_TEST_METHOD_NAMES = ImmutableList.of( "testSerializable", "testSerialization", "testEqualsAndSerializable", "testEqualsAndSerialization"); /* The names of the expected method that tests equals. */ private static final ImmutableList<String> EQUALS_TEST_METHOD_NAMES = ImmutableList.of( "testEquals", "testEqualsAndHashCode", "testEqualsAndSerializable", "testEqualsAndSerialization", "testEquality"); private static final Chopper TEST_SUFFIX = suffix("Test") .or(suffix("Tests")) .or(suffix("TestCase")) .or(suffix("TestSuite")); private final Logger logger = Logger.getLogger(getClass().getName()); private final ClassSanityTester tester = new ClassSanityTester(); private Visibility visibility = Visibility.PACKAGE; private Predicate<Class<?>> classFilter = new Predicate<Class<?>>() { @Override public boolean apply(Class<?> cls) { return visibility.isVisible(cls.getModifiers()); } }; /** * Restricts the sanity tests for public API only. By default, package-private API are also * covered. */ protected final void publicApiOnly() { visibility = Visibility.PUBLIC; } /** * Tests all top-level {@link Serializable} classes in the package. For a serializable Class * {@code C}: * <ul> * <li>If {@code C} explicitly implements {@link Object#equals}, the deserialized instance will be * checked to be equal to the instance before serialization. * <li>If {@code C} doesn't explicitly implement {@code equals} but instead inherits it from a * superclass, no equality check is done on the deserialized instance because it's not clear * whether the author intended for the class to be a value type. * <li>If a constructor or factory method takes a parameter whose type is interface, a dynamic * proxy will be passed to the method. It's possible that the method body expects an instance * method of the passed-in proxy to be of a certain value yet the proxy isn't aware of the * assumption, in which case the equality check before and after serialization will fail. * <li>If the constructor or factory method takes a parameter that {@link * AbstractPackageSanityTests} doesn't know how to construct, the test will fail. * <li>If there is no visible constructor or visible static factory method declared by {@code C}, * {@code C} is skipped for serialization test, even if it implements {@link Serializable}. * <li>Serialization test is not performed on method return values unless the method is a visible * static factory method whose return type is {@code C} or {@code C}'s subtype. * </ul> * * <p>In all cases, if {@code C} needs custom logic for testing serialization, you can add an * explicit {@code testSerializable()} test in the corresponding {@code CTest} class, and {@code * C} will be excluded from automated serialization test performed by this method. */ @Test public void testSerializable() throws Exception { // TODO: when we use @BeforeClass, we can pay the cost of class path scanning only once. for (Class<?> classToTest : findClassesToTest(loadClassesInPackage(), SERIALIZABLE_TEST_METHOD_NAMES)) { if (Serializable.class.isAssignableFrom(classToTest)) { try { Object instance = tester.instantiate(classToTest); if (instance != null) { if (isEqualsDefined(classToTest)) { SerializableTester.reserializeAndAssert(instance); } else { SerializableTester.reserialize(instance); } } } catch (Throwable e) { throw sanityError(classToTest, SERIALIZABLE_TEST_METHOD_NAMES, "serializable test", e); } } } } /** * Performs {@link NullPointerTester} checks for all top-level classes in the package. For a class * {@code C} * <ul> * <li>All visible static methods are checked such that passing null for any parameter that's not * annotated with {@link javax.annotation.Nullable} should throw {@link NullPointerException}. * <li>If there is any visible constructor or visible static factory method declared by the class, * all visible instance methods will be checked too using the instance created by invoking the * constructor or static factory method. * <li>If the constructor or factory method used to construct instance takes a parameter that * {@link AbstractPackageSanityTests} doesn't know how to construct, the test will fail. * <li>If there is no visible constructor or visible static factory method declared by {@code C}, * instance methods are skipped for nulls test. * <li>Nulls test is not performed on method return values unless the method is a visible static * factory method whose return type is {@code C} or {@code C}'s subtype. * </ul> * * <p>In all cases, if {@code C} needs custom logic for testing nulls, you can add an explicit * {@code testNulls()} test in the corresponding {@code CTest} class, and {@code C} will be * excluded from the automated null tests performed by this method. */ @Test public void testNulls() throws Exception { for (Class<?> classToTest : findClassesToTest(loadClassesInPackage(), NULL_TEST_METHOD_NAMES)) { try { tester.doTestNulls(classToTest, visibility); } catch (Throwable e) { throw sanityError(classToTest, NULL_TEST_METHOD_NAMES, "nulls test", e); } } } /** * Tests {@code equals()} and {@code hashCode()} implementations for every top-level class in the * package, that explicitly implements {@link Object#equals}. For a class {@code C}: * <ul> * <li>The visible constructor or visible static factory method with the most parameters is used * to construct the sample instances. In case of tie, the candidate constructors or factories * are tried one after another until one can be used to construct sample instances. * <li>For the constructor or static factory method used to construct instances, it's checked that * when equal parameters are passed, the result instance should also be equal; and vice versa. * <li>Inequality check is not performed against state mutation methods such as {@link List#add}, * or functional update methods such as {@link com.google.common.base.Joiner#skipNulls}. * <li>If the constructor or factory method used to construct instance takes a parameter that * {@link AbstractPackageSanityTests} doesn't know how to construct, the test will fail. * <li>If there is no visible constructor or visible static factory method declared by {@code C}, * {@code C} is skipped for equality test. * <li>Equality test is not performed on method return values unless the method is a visible * static factory method whose return type is {@code C} or {@code C}'s subtype. * </ul> * * <p>In all cases, if {@code C} needs custom logic for testing {@code equals()}, you can add an * explicit {@code testEquals()} test in the corresponding {@code CTest} class, and {@code C} will * be excluded from the automated {@code equals} test performed by this method. */ @Test public void testEquals() throws Exception { for (Class<?> classToTest : findClassesToTest(loadClassesInPackage(), EQUALS_TEST_METHOD_NAMES)) { if (!classToTest.isEnum() && isEqualsDefined(classToTest)) { try { tester.doTestEquals(classToTest); } catch (Throwable e) { throw sanityError(classToTest, EQUALS_TEST_METHOD_NAMES, "equals test", e); } } } } /** * Sets the default value for {@code type}, when dummy value for a parameter of the same type * needs to be created in order to invoke a method or constructor. The default value isn't used in * testing {@link Object#equals} because more than one sample instances are needed for testing * inequality. */ protected final <T> void setDefault(Class<T> type, T value) { tester.setDefault(type, value); } /** Specifies that classes that satisfy the given predicate aren't tested for sanity. */ protected final void ignoreClasses(Predicate<? super Class<?>> condition) { this.classFilter = and(this.classFilter, not(condition)); } private static AssertionFailedError sanityError( Class<?> cls, List<String> explicitTestNames, String description, Throwable e) { String message = String.format( "Error in automated %s of %s\n" + "If the class is better tested explicitly, you can add %s() to %sTest", description, cls, explicitTestNames.get(0), cls.getName()); AssertionFailedError error = new AssertionFailedError(message); error.initCause(e); return error; } /** * Finds the classes not ending with a test suffix and not covered by an explicit test * whose name is {@code explicitTestName}. */ @VisibleForTesting List<Class<?>> findClassesToTest( Iterable<? extends Class<?>> classes, Iterable<String> explicitTestNames) { // "a.b.Foo" -> a.b.Foo.class TreeMap<String, Class<?>> classMap = Maps.newTreeMap(); for (Class<?> cls : classes) { classMap.put(cls.getName(), cls); } // Foo.class -> [FooTest.class, FooTests.class, FooTestSuite.class, ...] Multimap<Class<?>, Class<?>> testClasses = HashMultimap.create(); LinkedHashSet<Class<?>> candidateClasses = Sets.newLinkedHashSet(); for (Class<?> cls : classes) { Optional<String> testedClassName = TEST_SUFFIX.chop(cls.getName()); if (testedClassName.isPresent()) { Class<?> testedClass = classMap.get(testedClassName.get()); if (testedClass != null) { testClasses.put(testedClass, cls); } } else { candidateClasses.add(cls); } } List<Class<?>> result = Lists.newArrayList(); NEXT_CANDIDATE: for (Class<?> candidate : Iterables.filter(candidateClasses, classFilter)) { for (Class<?> testClass : testClasses.get(candidate)) { if (hasTest(testClass, explicitTestNames)) { // covered by explicit test continue NEXT_CANDIDATE; } } result.add(candidate); } return result; } private List<Class<?>> loadClassesInPackage() throws IOException { List<Class<?>> classes = Lists.newArrayList(); String packageName = getClass().getPackage().getName(); for (ClassPath.ClassInfo classInfo : ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(packageName)) { Class<?> cls; try { cls = classInfo.load(); } catch (NoClassDefFoundError e) { // In case there were linking problems, this is probably not a class we care to test anyway. logger.log(Level.SEVERE, "Cannot load class " + classInfo + ", skipping...", e); continue; } if (!cls.isInterface()) { classes.add(cls); } } return classes; } private static boolean hasTest(Class<?> testClass, Iterable<String> testNames) { for (String testName : testNames) { try { testClass.getMethod(testName); return true; } catch (NoSuchMethodException e) { continue; } } return false; } private static boolean isEqualsDefined(Class<?> cls) { try { return !cls.getDeclaredMethod("equals", Object.class).isSynthetic(); } catch (NoSuchMethodException e) { return false; } } static abstract class Chopper { final Chopper or(final Chopper you) { final Chopper i = this; return new Chopper() { @Override Optional<String> chop(String str) { return i.chop(str).or(you.chop(str)); } }; } abstract Optional<String> chop(String str); static Chopper suffix(final String suffix) { return new Chopper() { @Override Optional<String> chop(String str) { if (str.endsWith(suffix)) { return Optional.of(str.substring(0, str.length() - suffix.length())); } else { return Optional.absent(); } } }; } } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MutableClassToInstanceMap; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.google.common.reflect.Invokable; import com.google.common.reflect.Parameter; import com.google.common.reflect.Reflection; import com.google.common.reflect.TypeToken; import com.google.common.testing.NullPointerTester.Visibility; import com.google.common.testing.RelationshipTester.Item; import com.google.common.testing.RelationshipTester.ItemReporter; import junit.framework.Assert; import junit.framework.AssertionFailedError; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Tester that runs automated sanity tests for any given class. A typical use case is to test static * factory classes like: <pre> * interface Book {...} * public class Books { * public static Book hardcover(String title) {...} * public static Book paperback(String title) {...} * } * </pre> * <p>And all the created {@code Book} instances can be tested with: <pre> * new ClassSanityTester() * .forAllPublicStaticMethods(Books.class) * .thatReturn(Book.class) * .testEquals(); // or testNulls(), testSerializable() etc. * </pre> * * @author Ben Yu * @since 14.0 */ @Beta public final class ClassSanityTester { private static final Ordering<Invokable<?, ?>> BY_METHOD_NAME = new Ordering<Invokable<?, ?>>() { @Override public int compare(Invokable<?, ?> left, Invokable<?, ?> right) { return left.getName().compareTo(right.getName()); } }; private static final Ordering<Invokable<?, ?>> BY_PARAMETERS = new Ordering<Invokable<?, ?>>() { @Override public int compare(Invokable<?, ?> left, Invokable<?, ?> right) { return Ordering.usingToString().compare(left.getParameters(), right.getParameters()); } }; private static final Ordering<Invokable<?, ?>> BY_NUMBER_OF_PARAMETERS = new Ordering<Invokable<?, ?>>() { @Override public int compare(Invokable<?, ?> left, Invokable<?, ?> right) { return Ints.compare(left.getParameters().size(), right.getParameters().size()); } }; private final MutableClassToInstanceMap<Object> defaultValues = MutableClassToInstanceMap.create(); private final ListMultimap<Class<?>, Object> sampleInstances = ArrayListMultimap.create(); private final NullPointerTester nullPointerTester = new NullPointerTester(); public ClassSanityTester() { // TODO(benyu): bake these into ArbitraryInstances. setDefault(byte.class, (byte) 1); setDefault(Byte.class, (byte) 1); setDefault(short.class, (short) 1); setDefault(Short.class, (short) 1); setDefault(int.class, 1); setDefault(Integer.class, 1); setDefault(long.class, 1L); setDefault(Long.class, 1L); setDefault(float.class, 1F); setDefault(Float.class, 1F); setDefault(double.class, 1D); setDefault(Double.class, 1D); setDefault(Class.class, Class.class); } /** * Sets the default value for {@code type}. The default value isn't used in testing {@link * Object#equals} because more than one sample instances are needed for testing inequality. * To set sample instances for equality testing, use {@link #setSampleInstances} instead. */ public <T> ClassSanityTester setDefault(Class<T> type, T value) { nullPointerTester.setDefault(type, value); defaultValues.putInstance(type, value); return this; } /** * Sets sample instances for {@code type} for purpose of {@code equals} testing, where different * values are needed to test inequality. * * <p>Used for types that {@link ClassSanityTester} doesn't already know how to sample. * It's usually necessary to add two unequal instances for each type, with the exception that if * the sample instance is to be passed to a {@link Nullable} parameter, one non-null sample is * sufficient. Setting an empty list will clear sample instances for {@code type}. */ public <T> ClassSanityTester setSampleInstances(Class<T> type, Iterable<? extends T> instances) { ImmutableList<? extends T> samples = ImmutableList.copyOf(instances); sampleInstances.putAll(checkNotNull(type), samples); if (!samples.isEmpty()) { setDefault(type, samples.get(0)); } return this; } /** * Tests that {@code cls} properly checks null on all constructor and method parameters that * aren't annotated with {@link Nullable}. In details: * <ul> * <li>All non-private static methods are checked such that passing null for any parameter that's * not annotated with {@link javax.annotation.Nullable} should throw {@link * NullPointerException}. * <li>If there is any non-private constructor or non-private static factory method declared by * {@code cls}, all non-private instance methods will be checked too using the instance * created by invoking the constructor or static factory method. * <li>If there is any non-private constructor or non-private static factory method declared by * {@code cls}: * <ul> * <li>Test will fail if default value for a parameter cannot be determined. * <li>Test will fail if the factory method returns null so testing instance methods is * impossible. * <li>Test will fail if the constructor or factory method throws exception. * </ul> * <li>If there is no non-private constructor or non-private static factory method declared by * {@code cls}, instance methods are skipped for nulls test. * <li>Nulls test is not performed on method return values unless the method is a non-private * static factory method whose return type is {@code cls} or {@code cls}'s subtype. * </ul> */ public void testNulls(Class<?> cls) { try { doTestNulls(cls, Visibility.PACKAGE); } catch (Exception e) { throw Throwables.propagate(e); } } void doTestNulls(Class<?> cls, Visibility visibility) throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException { if (!Modifier.isAbstract(cls.getModifiers())) { nullPointerTester.testConstructors(cls, visibility); } nullPointerTester.testStaticMethods(cls, visibility); if (hasInstanceMethodToTestNulls(cls, visibility)) { Object instance = instantiate(cls); if (instance != null) { nullPointerTester.testInstanceMethods(instance, visibility); } } } private boolean hasInstanceMethodToTestNulls(Class<?> c, Visibility visibility) { for (Method method : nullPointerTester.getInstanceMethodsToTest(c, visibility)) { for (Parameter param : Invokable.from(method).getParameters()) { if (!NullPointerTester.isPrimitiveOrNullable(param)) { return true; } } } return false; } /** * Tests the {@link Object#equals} and {@link Object#hashCode} of {@code cls}. In details: * <ul> * <li>The non-private constructor or non-private static factory method with the most parameters * is used to construct the sample instances. In case of tie, the candidate constructors or * factories are tried one after another until one can be used to construct sample instances. * <li>For the constructor or static factory method used to construct instances, it's checked that * when equal parameters are passed, the result instance should also be equal; and vice versa. * <li>If a non-private constructor or non-private static factory method exists: <ul> * <li>Test will fail if default value for a parameter cannot be determined. * <li>Test will fail if the factory method returns null so testing instance methods is * impossible. * <li>Test will fail if the constructor or factory method throws exception. * </ul> * <li>If there is no non-private constructor or non-private static factory method declared by * {@code cls}, no test is performed. * <li>Equality test is not performed on method return values unless the method is a non-private * static factory method whose return type is {@code cls} or {@code cls}'s subtype. * <li>Inequality check is not performed against state mutation methods such as {@link List#add}, * or functional update methods such as {@link com.google.common.base.Joiner#skipNulls}. * </ul> * * <p>Note that constructors taking a builder object cannot be tested effectively because * semantics of builder can be arbitrarily complex. Still, a factory class can be created in the * test to facilitate equality testing. For example: <pre> * public class FooTest { * * private static class FooFactoryForTest { * public static Foo create(String a, String b, int c, boolean d) { * return Foo.builder() * .setA(a) * .setB(b) * .setC(c) * .setD(d) * .build(); * } * } * * public void testEquals() { * new ClassSanityTester() * .forAllPublicStaticMethods(FooFactoryForTest.class) * .thatReturn(Foo.class) * .testEquals(); * } * } * </pre> * <p>It will test that Foo objects created by the {@code create(a, b, c, d)} factory method with * equal parameters are equal and vice versa, thus indirectly tests the builder equality. */ public void testEquals(Class<?> cls) { try { doTestEquals(cls); } catch (Exception e) { throw Throwables.propagate(e); } } void doTestEquals(Class<?> cls) throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException { if (cls.isEnum()) { return; } List<? extends Invokable<?, ?>> factories = Lists.reverse(getFactories(TypeToken.of(cls))); if (factories.isEmpty()) { return; } int numberOfParameters = factories.get(0).getParameters().size(); List<ParameterNotInstantiableException> paramErrors = Lists.newArrayList(); List<InvocationTargetException> instantiationExceptions = Lists.newArrayList(); List<FactoryMethodReturnsNullException> nullErrors = Lists.newArrayList(); // Try factories with the greatest number of parameters first. for (Invokable<?, ?> factory : factories) { if (factory.getParameters().size() == numberOfParameters) { try { testEqualsUsing(factory); return; } catch (ParameterNotInstantiableException e) { paramErrors.add(e); } catch (InvocationTargetException e) { instantiationExceptions.add(e); } catch (FactoryMethodReturnsNullException e) { nullErrors.add(e); } } } throwFirst(paramErrors); throwFirst(instantiationExceptions); throwFirst(nullErrors); } /** * Instantiates {@code cls} by invoking one of its non-private constructors or non-private static * factory methods with the parameters automatically provided using dummy values. * * @return The instantiated instance, or {@code null} if the class has no non-private constructor * or factory method to be constructed. */ @Nullable <T> T instantiate(Class<T> cls) throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException { if (cls.isEnum()) { T[] constants = cls.getEnumConstants(); if (constants.length > 0) { return constants[0]; } else { return null; } } TypeToken<T> type = TypeToken.of(cls); List<ParameterNotInstantiableException> paramErrors = Lists.newArrayList(); List<InvocationTargetException> instantiationExceptions = Lists.newArrayList(); List<FactoryMethodReturnsNullException> nullErrors = Lists.newArrayList(); for (Invokable<?, ? extends T> factory : getFactories(type)) { T instance; try { instance = instantiate(factory); } catch (ParameterNotInstantiableException e) { paramErrors.add(e); continue; } catch (InvocationTargetException e) { instantiationExceptions.add(e); continue; } if (instance == null) { nullErrors.add(new FactoryMethodReturnsNullException(factory)); } else { return instance; } } throwFirst(paramErrors); throwFirst(instantiationExceptions); throwFirst(nullErrors); return null; } /** * Returns an object responsible for performing sanity tests against the return values * of all public static methods declared by {@code cls}, excluding superclasses. */ public FactoryMethodReturnValueTester forAllPublicStaticMethods(Class<?> cls) { ImmutableList.Builder<Invokable<?, ?>> builder = ImmutableList.builder(); for (Method method : cls.getDeclaredMethods()) { Invokable<?, ?> invokable = Invokable.from(method); invokable.setAccessible(true); if (invokable.isPublic() && invokable.isStatic() && !invokable.isSynthetic()) { builder.add(invokable); } } return new FactoryMethodReturnValueTester(cls, builder.build(), "public static methods"); } /** Runs sanity tests against return values of static factory methods declared by a class. */ public final class FactoryMethodReturnValueTester { private final Set<String> packagesToTest = Sets.newHashSet(); private final Class<?> declaringClass; private final ImmutableList<Invokable<?, ?>> factories; private final String factoryMethodsDescription; private Class<?> returnTypeToTest = Object.class; private FactoryMethodReturnValueTester( Class<?> declaringClass, ImmutableList<Invokable<?, ?>> factories, String factoryMethodsDescription) { this.declaringClass = declaringClass; this.factories = factories; this.factoryMethodsDescription = factoryMethodsDescription; packagesToTest.add(Reflection.getPackageName(declaringClass)); } /** * Specifies that only the methods that are declared to return {@code returnType} or its subtype * are tested. * * @return this tester object */ public FactoryMethodReturnValueTester thatReturn(Class<?> returnType) { this.returnTypeToTest = returnType; return this; } /** * Tests null checks against the instance methods of the return values, if any. * * <p>Test fails if default value cannot be determined for a constructor or factory method * parameter, or if the constructor or factory method throws exception. * * @return this tester */ public FactoryMethodReturnValueTester testNulls() throws Exception { for (Invokable<?, ?> factory : getFactoriesToTest()) { Object instance = instantiate(factory); if (instance != null && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) { try { nullPointerTester.testAllPublicInstanceMethods(instance); } catch (AssertionError e) { AssertionError error = new AssertionFailedError( "Null check failed on return value of " + factory); error.initCause(e); throw error; } } } return this; } /** * Tests {@link Object#equals} and {@link Object#hashCode} against the return values of the * static methods, by asserting that when equal parameters are passed to the same static method, * the return value should also be equal; and vice versa. * * <p>Test fails if default value cannot be determined for a constructor or factory method * parameter, or if the constructor or factory method throws exception. * * @return this tester */ public FactoryMethodReturnValueTester testEquals() throws Exception { for (Invokable<?, ?> factory : getFactoriesToTest()) { try { testEqualsUsing(factory); } catch (FactoryMethodReturnsNullException e) { // If the factory returns null, we just skip it. } } return this; } /** * Runs serialization test on the return values of the static methods. * * <p>Test fails if default value cannot be determined for a constructor or factory method * parameter, or if the constructor or factory method throws exception. * * @return this tester */ public FactoryMethodReturnValueTester testSerializable() throws Exception { for (Invokable<?, ?> factory : getFactoriesToTest()) { Object instance = instantiate(factory); if (instance != null) { try { SerializableTester.reserialize(instance); } catch (RuntimeException e) { AssertionError error = new AssertionFailedError( "Serialization failed on return value of " + factory); error.initCause(e.getCause()); throw error; } } } return this; } /** * Runs equals and serialization test on the return values. * * <p>Test fails if default value cannot be determined for a constructor or factory method * parameter, or if the constructor or factory method throws exception. * * @return this tester */ public FactoryMethodReturnValueTester testEqualsAndSerializable() throws Exception { for (Invokable<?, ?> factory : getFactoriesToTest()) { try { testEqualsUsing(factory); } catch (FactoryMethodReturnsNullException e) { // If the factory returns null, we just skip it. } Object instance = instantiate(factory); if (instance != null) { try { SerializableTester.reserializeAndAssert(instance); } catch (RuntimeException e) { AssertionError error = new AssertionFailedError( "Serialization failed on return value of " + factory); error.initCause(e.getCause()); throw error; } catch (AssertionFailedError e) { AssertionError error = new AssertionFailedError( "Return value of " + factory + " reserialized to an unequal value"); error.initCause(e); throw error; } } } return this; } private ImmutableList<Invokable<?, ?>> getFactoriesToTest() { ImmutableList.Builder<Invokable<?, ?>> builder = ImmutableList.builder(); for (Invokable<?, ?> factory : factories) { if (returnTypeToTest.isAssignableFrom(factory.getReturnType().getRawType())) { builder.add(factory); } } ImmutableList<Invokable<?, ?>> factoriesToTest = builder.build(); Assert.assertFalse("No " + factoryMethodsDescription + " that return " + returnTypeToTest.getName() + " or subtype are found in " + declaringClass + ".", factoriesToTest.isEmpty()); return factoriesToTest; } } /** * Instantiates using {@code factory}. If {@code factory} is annotated with {@link Nullable} and * returns null, null will be returned. * * @throws ParameterNotInstantiableException if the static methods cannot be invoked because * the default value of a parameter cannot be determined. * @throws IllegalAccessException if the class isn't public or is nested inside a non-public * class, preventing its methods from being accessible. * @throws InvocationTargetException if a static method threw exception. */ @Nullable private <T> T instantiate(Invokable<?, ? extends T> factory) throws ParameterNotInstantiableException, InvocationTargetException, IllegalAccessException { return invoke(factory, getDummyArguments(factory)); } private void testEqualsUsing(final Invokable<?, ?> factory) throws ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException { List<Parameter> params = factory.getParameters(); List<FreshValueGenerator> argGenerators = Lists.newArrayListWithCapacity(params.size()); List<Object> args = Lists.newArrayListWithCapacity(params.size()); for (Parameter param : params) { FreshValueGenerator generator = newFreshValueGenerator(); argGenerators.add(generator); args.add(generateDummyArg(param, generator)); } Object instance = createInstance(factory, args); List<Object> equalArgs = generateEqualFactoryArguments(factory, params, args); // Each group is a List of items, each item has a list of factory args. final List<List<List<Object>>> argGroups = Lists.newArrayList(); argGroups.add(ImmutableList.of(args, equalArgs)); EqualsTester tester = new EqualsTester().setItemReporter(new ItemReporter() { @Override String reportItem(Item item) { List<Object> factoryArgs = argGroups.get(item.groupNumber).get(item.itemNumber); return factory.getName() + "(" + Joiner.on(", ").useForNull("null").join(factoryArgs) + ")"; } }); tester.addEqualityGroup(instance, createInstance(factory, equalArgs)); for (int i = 0; i < params.size(); i++) { List<Object> newArgs = Lists.newArrayList(args); Object newArg = argGenerators.get(i).generate(params.get(i).getType().getRawType()); if (Objects.equal(args.get(i), newArg)) { // no value variance, no equality group continue; } newArgs.set(i, newArg); tester.addEqualityGroup(createInstance(factory, newArgs)); argGroups.add(ImmutableList.of(newArgs)); } tester.testEquals(); } /** * Returns dummy factory arguments that are equal to {@code args} but may be different instances, * to be used to construct a second instance of the same equality group. */ private List<Object> generateEqualFactoryArguments( Invokable<?, ?> factory, List<Parameter> params, List<Object> args) throws ParameterNotInstantiableException, FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException { List<Object> equalArgs = Lists.newArrayList(args); for (int i = 0; i < args.size(); i++) { Parameter param = params.get(i); Object arg = args.get(i); // Use new fresh value generator because 'args' were populated with new fresh generator each. // Two newFreshValueGenerator() instances should normally generate equal value sequence. Object shouldBeEqualArg = generateDummyArg(param, newFreshValueGenerator()); if (arg != shouldBeEqualArg && Objects.equal(arg, shouldBeEqualArg) && hashCodeInsensitiveToArgReference(factory, args, i, shouldBeEqualArg) && hashCodeInsensitiveToArgReference( factory, args, i, generateDummyArg(param, newFreshValueGenerator()))) { // If the implementation uses identityHashCode(), referential equality is // probably intended. So no point in using an equal-but-different factory argument. // We check twice to avoid confusion caused by accidental hash collision. equalArgs.set(i, shouldBeEqualArg); } } return equalArgs; } private static boolean hashCodeInsensitiveToArgReference( Invokable<?, ?> factory, List<Object> args, int i, Object alternateArg) throws FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException { List<Object> tentativeArgs = Lists.newArrayList(args); tentativeArgs.set(i, alternateArg); return createInstance(factory, tentativeArgs).hashCode() == createInstance(factory, args).hashCode(); } // sampleInstances is a type-safe class-values mapping, but we don't have a type-safe data // structure to hold the mappings. @SuppressWarnings({"unchecked", "rawtypes"}) private FreshValueGenerator newFreshValueGenerator() { FreshValueGenerator generator = new FreshValueGenerator() { @Override Object interfaceMethodCalled(Class<?> interfaceType, Method method) { return getDummyValue(TypeToken.of(interfaceType).method(method).getReturnType()); } }; for (Map.Entry<Class<?>, Collection<Object>> entry : sampleInstances.asMap().entrySet()) { generator.addSampleInstances((Class) entry.getKey(), entry.getValue()); } return generator; } private static @Nullable Object generateDummyArg(Parameter param, FreshValueGenerator generator) throws ParameterNotInstantiableException { if (param.isAnnotationPresent(Nullable.class)) { return null; } Object arg = generator.generate(param.getType()); if (arg == null) { throw new ParameterNotInstantiableException(param); } return arg; } private static <X extends Throwable> void throwFirst(List<X> exceptions) throws X { if (!exceptions.isEmpty()) { throw exceptions.get(0); } } /** Factories with the least number of parameters are listed first. */ private static <T> ImmutableList<Invokable<?, ? extends T>> getFactories(TypeToken<T> type) { List<Invokable<?, ? extends T>> factories = Lists.newArrayList(); for (Method method : type.getRawType().getDeclaredMethods()) { Invokable<?, ?> invokable = type.method(method); if (!invokable.isPrivate() && !invokable.isSynthetic() && invokable.isStatic() && type.isAssignableFrom(invokable.getReturnType())) { @SuppressWarnings("unchecked") // guarded by isAssignableFrom() Invokable<?, ? extends T> factory = (Invokable<?, ? extends T>) invokable; factories.add(factory); } } if (!Modifier.isAbstract(type.getRawType().getModifiers())) { for (Constructor<?> constructor : type.getRawType().getDeclaredConstructors()) { Invokable<T, T> invokable = type.constructor(constructor); if (!invokable.isPrivate() && !invokable.isSynthetic()) { factories.add(invokable); } } } for (Invokable<?, ?> factory : factories) { factory.setAccessible(true); } // Sorts methods/constructors with least number of parameters first since it's likely easier to // fill dummy parameter values for them. Ties are broken by name then by the string form of the // parameter list. return BY_NUMBER_OF_PARAMETERS.compound(BY_METHOD_NAME).compound(BY_PARAMETERS) .immutableSortedCopy(factories); } private List<Object> getDummyArguments(Invokable<?, ?> invokable) throws ParameterNotInstantiableException { List<Object> args = Lists.newArrayList(); for (Parameter param : invokable.getParameters()) { if (param.isAnnotationPresent(Nullable.class)) { args.add(null); continue; } Object defaultValue = getDummyValue(param.getType()); if (defaultValue == null) { throw new ParameterNotInstantiableException(param); } args.add(defaultValue); } return args; } private <T> T getDummyValue(TypeToken<T> type) { Class<? super T> rawType = type.getRawType(); @SuppressWarnings("unchecked") // Assume all default values are generics safe. T defaultValue = (T) defaultValues.getInstance(rawType); if (defaultValue != null) { return defaultValue; } @SuppressWarnings("unchecked") // ArbitraryInstances always returns generics-safe dummies. T value = (T) ArbitraryInstances.get(rawType); if (value != null) { return value; } if (rawType.isInterface()) { return new SerializableDummyProxy(this).newProxy(type); } return null; } private static <T> T createInstance(Invokable<?, ? extends T> factory, List<?> args) throws FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException { T instance = invoke(factory, args); if (instance == null) { throw new FactoryMethodReturnsNullException(factory); } return instance; } @Nullable private static <T> T invoke(Invokable<?, ? extends T> factory, List<?> args) throws InvocationTargetException, IllegalAccessException { T returnValue = factory.invoke(null, args.toArray()); if (returnValue == null) { Assert.assertTrue(factory + " returns null but it's not annotated with @Nullable", factory.isAnnotationPresent(Nullable.class)); } return returnValue; } /** * Thrown if the test tries to invoke a constructor or static factory method but failed because * the dummy value of a constructor or method parameter is unknown. */ @VisibleForTesting static class ParameterNotInstantiableException extends Exception { public ParameterNotInstantiableException(Parameter parameter) { super("Cannot determine value for parameter " + parameter + " of " + parameter.getDeclaringInvokable()); } } /** * Thrown if the test tries to invoke a static factory method to test instance methods but the * factory returned null. */ @VisibleForTesting static class FactoryMethodReturnsNullException extends Exception { public FactoryMethodReturnsNullException(Invokable<?, ?> factory) { super(factory + " returns null and cannot be used to test instance methods."); } } private static final class SerializableDummyProxy extends DummyProxy implements Serializable { private transient final ClassSanityTester tester; SerializableDummyProxy(ClassSanityTester tester) { this.tester = tester; } @Override <R> R dummyReturnValue(TypeToken<R> returnType) { return tester.getDummyValue(returnType); } @Override public boolean equals(Object obj) { return obj instanceof SerializableDummyProxy; } @Override public int hashCode() { return 0; } } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.CharMatcher; import com.google.common.base.Charsets; import com.google.common.base.Equivalence; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Throwables; import com.google.common.base.Ticker; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.BiMap; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashBiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMultiset; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; import com.google.common.collect.Ordering; import com.google.common.collect.RowSortedTable; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.collect.SortedMultiset; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import com.google.common.collect.TreeMultiset; import com.google.common.primitives.UnsignedInteger; import com.google.common.primitives.UnsignedLong; import com.google.common.reflect.AbstractInvocationHandler; import com.google.common.reflect.Invokable; import com.google.common.reflect.Parameter; import com.google.common.reflect.Reflection; import com.google.common.reflect.TypeToken; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.TypeVariable; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Currency; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Generates fresh instances of types that are different from each other (if possible). * * @author Ben Yu */ class FreshValueGenerator { private static final ImmutableMap<Class<?>, Method> GENERATORS; static { ImmutableMap.Builder<Class<?>, Method> builder = ImmutableMap.builder(); for (Method method : FreshValueGenerator.class.getDeclaredMethods()) { if (method.isAnnotationPresent(Generates.class)) { builder.put(method.getReturnType(), method); } } GENERATORS = builder.build(); } private final AtomicInteger differentiator = new AtomicInteger(1); private final ListMultimap<Class<?>, Object> sampleInstances = ArrayListMultimap.create(); <T> void addSampleInstances(Class<T> type, Iterable<? extends T> instances) { sampleInstances.putAll(checkNotNull(type), checkNotNull(instances)); } /** * Returns a fresh instance for {@code type} if possible. The returned instance could be: * <ul> * <li>exactly of the given type, including generic type parameters, such as * {@code ImmutableList<String>}; * <li>of the raw type; * <li>null if no fresh value can be generated. * </ul> */ @Nullable final <T> T generate(TypeToken<T> type) { // Not completely safe since sample instances are registered by raw types. // But we assume the generic type parameters are mostly unimportant for these dummy values, // because what really matters are equals/hashCode. @SuppressWarnings("unchecked") T result = (T) generateIfPossible(type); return result; } @Nullable final <T> T generate(Class<T> type) { return generate(TypeToken.of(type)); } @Nullable private Object generateIfPossible(TypeToken<?> type) { Class<?> rawType = type.getRawType(); List<Object> samples = sampleInstances.get(rawType); Object sample = nextInstance(samples, null); if (sample != null) { return sample; } if (rawType.isEnum()) { return nextInstance(rawType.getEnumConstants(), null); } if (type.isArray()) { TypeToken<?> componentType = type.getComponentType(); Object array = Array.newInstance(componentType.getRawType(), 1); Array.set(array, 0, generateIfPossible(componentType)); return array; } Method generator = GENERATORS.get(rawType); if (generator != null) { ImmutableList<Parameter> params = Invokable.from(generator).getParameters(); List<Object> args = Lists.newArrayListWithCapacity(params.size()); TypeVariable<?>[] typeVars = rawType.getTypeParameters(); for (int i = 0; i < params.size(); i++) { TypeToken<?> paramType = type.resolveType(typeVars[i]); // We require all @Generates methods to either be parameter-less or accept non-null // fresh values for their generic parameter types. Object argValue = generateIfPossible(paramType); if (argValue == null) { return defaultGenerate(rawType); } args.add(argValue); } try { return generator.invoke(this, args.toArray()); } catch (InvocationTargetException e) { Throwables.propagate(e.getCause()); } catch (Exception e) { throw Throwables.propagate(e); } } return defaultGenerate(rawType); } private Object defaultGenerate(Class<?> rawType) { if (rawType.isInterface()) { // always create a new proxy return newProxy(rawType); } return ArbitraryInstances.get(rawType); } final <T> T newProxy(final Class<T> interfaceType) { return Reflection.newProxy(interfaceType, new FreshInvocationHandler(interfaceType)); } private final class FreshInvocationHandler extends AbstractInvocationHandler { private final int identity = freshInt(); private final Class<?> interfaceType; FreshInvocationHandler(Class<?> interfaceType) { this.interfaceType = interfaceType; } @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) { return interfaceMethodCalled(interfaceType, method); } @Override public int hashCode() { return identity; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof FreshInvocationHandler) { FreshInvocationHandler that = (FreshInvocationHandler) obj; return identity == that.identity; } return false; } @Override public String toString() { return paramString(interfaceType, identity); } } /** Subclasses can override to provide different return value for proxied interface methods. */ Object interfaceMethodCalled( @SuppressWarnings("unused") Class<?> interfaceType, @SuppressWarnings("unused") Method method) { throw new UnsupportedOperationException(); } private <T> T nextInstance(T[] instances, T defaultValue) { return nextInstance(Arrays.asList(instances), defaultValue); } private <T> T nextInstance(Collection<T> instances, T defaultValue) { if (instances.isEmpty()) { return defaultValue; } // freshInt() is 1-based. return Iterables.get(instances, (freshInt() - 1) % instances.size()); } private static String paramString(Class<?> type, int i) { return type.getSimpleName() + '@' + i; } /** * Annotates a method to be the instance generator of a certain type. The return type is the * generated type. The method parameters are non-null fresh values for each method type variable * in the same type variable declaration order of the return type. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) private @interface Generates {} @Generates private Class<?> freshClass() { return nextInstance( ImmutableList.of( int.class, long.class, void.class, Object.class, Object[].class, Iterable.class), Object.class); } @Generates private Object freshObject() { return freshString(); } @Generates private Number freshNumber() { return freshInt(); } @Generates private int freshInt() { return differentiator.getAndIncrement(); } @Generates private Integer freshInteger() { return new Integer(freshInt()); } @Generates private long freshLong() { return freshInt(); } @Generates private Long freshLongObject() { return new Long(freshLong()); } @Generates private float freshFloat() { return freshInt(); } @Generates private Float freshFloatObject() { return new Float(freshFloat()); } @Generates private double freshDouble() { return freshInt(); } @Generates private Double freshDoubleObject() { return new Double(freshDouble()); } @Generates private short freshShort() { return (short) freshInt(); } @Generates private Short freshShortObject() { return new Short(freshShort()); } @Generates private byte freshByte() { return (byte) freshInt(); } @Generates private Byte freshByteObject() { return new Byte(freshByte()); } @Generates private char freshChar() { return freshString().charAt(0); } @Generates private Character freshCharacter() { return new Character(freshChar()); } @Generates private boolean freshBoolean() { return freshInt() % 2 == 0; } @Generates private Boolean freshBooleanObject() { return new Boolean(freshBoolean()); } @Generates private UnsignedInteger freshUnsignedInteger() { return UnsignedInteger.fromIntBits(freshInt()); } @Generates private UnsignedLong freshUnsignedLong() { return UnsignedLong.fromLongBits(freshLong()); } @Generates private BigInteger freshBigInteger() { return BigInteger.valueOf(freshInt()); } @Generates private BigDecimal freshBigDecimal() { return BigDecimal.valueOf(freshInt()); } @Generates private CharSequence freshCharSequence() { return freshString(); } @Generates private String freshString() { return Integer.toString(freshInt()); } @Generates private Comparable<?> freshComparable() { return freshString(); } @Generates private Pattern freshPattern() { return Pattern.compile(freshString()); } @Generates private Charset freshCharset() { return nextInstance(Charset.availableCharsets().values(), Charsets.UTF_8); } @Generates private Locale freshLocale() { return nextInstance(Locale.getAvailableLocales(), Locale.US); } @Generates private Currency freshCurrency() { for (Set<Locale> uselessLocales = Sets.newHashSet(); ; ) { Locale locale = freshLocale(); if (uselessLocales.contains(locale)) { // exhausted all locales return Currency.getInstance(Locale.US); } try { return Currency.getInstance(locale); } catch (IllegalArgumentException e) { uselessLocales.add(locale); } } } // common.base @Generates private Joiner freshJoiner() { return Joiner.on(freshString()); } @Generates private Splitter freshSplitter() { return Splitter.on(freshString()); } @Generates private <T> Equivalence<T> freshEquivalence() { return new Equivalence<T>() { @Override protected boolean doEquivalent(T a, T b) { return false; } @Override protected int doHash(T t) { return 0; } final String string = paramString(Equivalence.class, freshInt()); @Override public String toString() { return string; } }; } @Generates private CharMatcher freshCharMatcher() { return new CharMatcher() { @Override public boolean matches(char c) { return false; } final String string = paramString(CharMatcher.class, freshInt()); @Override public String toString() { return string; } }; } @Generates private Ticker freshTicker() { return new Ticker() { @Override public long read() { return 0; } final String string = paramString(Ticker.class, freshInt()); @Override public String toString() { return string; } }; } // collect @Generates private <T> Comparator<T> freshComparator() { return freshOrdering(); } @Generates private <T> Ordering<T> freshOrdering() { return new Ordering<T>() { @Override public int compare(T left, T right) { return 0; } final String string = paramString(Ordering.class, freshInt()); @Override public String toString() { return string; } }; } @Generates static private <E> Iterable<E> freshIterable(E freshElement) { return freshList(freshElement); } @Generates static private <E> Collection<E> freshCollection(E freshElement) { return freshList(freshElement); } @Generates static private <E> List<E> freshList(E freshElement) { return freshArrayList(freshElement); } @Generates static private <E> ArrayList<E> freshArrayList(E freshElement) { ArrayList<E> list = Lists.newArrayList(); list.add(freshElement); return list; } @Generates static private <E> LinkedList<E> freshLinkedList(E freshElement) { LinkedList<E> list = Lists.newLinkedList(); list.add(freshElement); return list; } @Generates static private <E> ImmutableList<E> freshImmutableList(E freshElement) { return ImmutableList.of(freshElement); } @Generates static private <E> ImmutableCollection<E> freshImmutableCollection(E freshElement) { return freshImmutableList(freshElement); } @Generates static private <E> Set<E> freshSet(E freshElement) { return freshHashSet(freshElement); } @Generates static private <E> HashSet<E> freshHashSet(E freshElement) { return freshLinkedHashSet(freshElement); } @Generates static private <E> LinkedHashSet<E> freshLinkedHashSet(E freshElement) { LinkedHashSet<E> set = Sets.newLinkedHashSet(); set.add(freshElement); return set; } @Generates static private <E> ImmutableSet<E> freshImmutableSet(E freshElement) { return ImmutableSet.of(freshElement); } @Generates static private <E extends Comparable<? super E>> SortedSet<E> freshSortedSet(E freshElement) { return freshNavigableSet(freshElement); } @Generates static private <E extends Comparable<? super E>> NavigableSet<E> freshNavigableSet(E freshElement) { return freshTreeSet(freshElement); } @Generates static private <E extends Comparable<? super E>> TreeSet<E> freshTreeSet( E freshElement) { TreeSet<E> set = Sets.newTreeSet(); set.add(freshElement); return set; } @Generates static private <E extends Comparable<? super E>> ImmutableSortedSet<E> freshImmutableSortedSet(E freshElement) { return ImmutableSortedSet.of(freshElement); } @Generates static private <E> Multiset<E> freshMultiset(E freshElement) { return freshHashMultiset(freshElement); } @Generates static private <E> HashMultiset<E> freshHashMultiset(E freshElement) { HashMultiset<E> multiset = HashMultiset.create(); multiset.add(freshElement); return multiset; } @Generates static private <E> LinkedHashMultiset<E> freshLinkedHashMultiset(E freshElement) { LinkedHashMultiset<E> multiset = LinkedHashMultiset.create(); multiset.add(freshElement); return multiset; } @Generates static private <E> ImmutableMultiset<E> freshImmutableMultiset(E freshElement) { return ImmutableMultiset.of(freshElement); } @Generates static private <E extends Comparable<E>> SortedMultiset<E> freshSortedMultiset( E freshElement) { return freshTreeMultiset(freshElement); } @Generates static private <E extends Comparable<E>> TreeMultiset<E> freshTreeMultiset( E freshElement) { TreeMultiset<E> multiset = TreeMultiset.create(); multiset.add(freshElement); return multiset; } @Generates static private <E extends Comparable<E>> ImmutableSortedMultiset<E> freshImmutableSortedMultiset(E freshElement) { return ImmutableSortedMultiset.of(freshElement); } @Generates static private <K, V> Map<K, V> freshMap(K key, V value) { return freshHashdMap(key, value); } @Generates static private <K, V> HashMap<K, V> freshHashdMap(K key, V value) { return freshLinkedHashMap(key, value); } @Generates static private <K, V> LinkedHashMap<K, V> freshLinkedHashMap(K key, V value) { LinkedHashMap<K, V> map = Maps.newLinkedHashMap(); map.put(key, value); return map; } @Generates static private <K, V> ImmutableMap<K, V> freshImmutableMap(K key, V value) { return ImmutableMap.of(key, value); } @Generates static private <K, V> ConcurrentMap<K, V> freshConcurrentMap(K key, V value) { ConcurrentMap<K, V> map = Maps.newConcurrentMap(); map.put(key, value); return map; } @Generates static private <K extends Comparable<? super K>, V> SortedMap<K, V> freshSortedMap(K key, V value) { return freshNavigableMap(key, value); } @Generates static private <K extends Comparable<? super K>, V> NavigableMap<K, V> freshNavigableMap(K key, V value) { return freshTreeMap(key, value); } @Generates static private <K extends Comparable<? super K>, V> TreeMap<K, V> freshTreeMap( K key, V value) { TreeMap<K, V> map = Maps.newTreeMap(); map.put(key, value); return map; } @Generates static private <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> freshImmutableSortedMap(K key, V value) { return ImmutableSortedMap.of(key, value); } @Generates static private <K, V> Multimap<K, V> freshMultimap(K key, V value) { return freshListMultimap(key, value); } @Generates static private <K, V> ImmutableMultimap<K, V> freshImmutableMultimap(K key, V value) { return ImmutableMultimap.of(key, value); } @Generates static private <K, V> ListMultimap<K, V> freshListMultimap(K key, V value) { return freshArrayListMultimap(key, value); } @Generates static private <K, V> ArrayListMultimap<K, V> freshArrayListMultimap(K key, V value) { ArrayListMultimap<K, V> multimap = ArrayListMultimap.create(); multimap.put(key, value); return multimap; } @Generates static private <K, V> ImmutableListMultimap<K, V> freshImmutableListMultimap( K key, V value) { return ImmutableListMultimap.of(key, value); } @Generates static private <K, V> SetMultimap<K, V> freshSetMultimap(K key, V value) { return freshLinkedHashMultimap(key, value); } @Generates static private <K, V> HashMultimap<K, V> freshHashMultimap(K key, V value) { HashMultimap<K, V> multimap = HashMultimap.create(); multimap.put(key, value); return multimap; } @Generates static private <K, V> LinkedHashMultimap<K, V> freshLinkedHashMultimap( K key, V value) { LinkedHashMultimap<K, V> multimap = LinkedHashMultimap.create(); multimap.put(key, value); return multimap; } @Generates static private <K, V> ImmutableSetMultimap<K, V> freshImmutableSetMultimap( K key, V value) { return ImmutableSetMultimap.of(key, value); } @Generates static private <K, V> BiMap<K, V> freshBimap(K key, V value) { return freshHashBiMap(key, value); } @Generates static private <K, V> HashBiMap<K, V> freshHashBiMap(K key, V value) { HashBiMap<K, V> bimap = HashBiMap.create(); bimap.put(key, value); return bimap; } @Generates static private <K, V> ImmutableBiMap<K, V> freshImmutableBimap( K key, V value) { return ImmutableBiMap.of(key, value); } @Generates static private <R, C, V> Table<R, C, V> freshTable(R row, C column, V value) { return freshHashBasedTable(row, column, value); } @Generates static private <R, C, V> HashBasedTable<R, C, V> freshHashBasedTable( R row, C column, V value) { HashBasedTable<R, C, V> table = HashBasedTable.create(); table.put(row, column, value); return table; } @SuppressWarnings("rawtypes") // TreeBasedTable.create() is defined as such @Generates static private <R extends Comparable, C extends Comparable, V> RowSortedTable<R, C, V> freshRowSortedTable(R row, C column, V value) { return freshTreeBasedTable(row, column, value); } @SuppressWarnings("rawtypes") // TreeBasedTable.create() is defined as such @Generates static private <R extends Comparable, C extends Comparable, V> TreeBasedTable<R, C, V> freshTreeBasedTable(R row, C column, V value) { TreeBasedTable<R, C, V> table = TreeBasedTable.create(); table.put(row, column, value); return table; } @Generates static private <R, C, V> ImmutableTable<R, C, V> freshImmutableTable( R row, C column, V value) { return ImmutableTable.of(row, column, value); } // common.reflect @Generates private TypeToken<?> freshTypeToken() { return TypeToken.of(freshClass()); } // io types @Generates private File freshFile() { return new File(freshString()); } @Generates private static ByteArrayInputStream freshByteArrayInputStream() { return new ByteArrayInputStream(new byte[0]); } @Generates private static InputStream freshInputStream() { return freshByteArrayInputStream(); } @Generates private StringReader freshStringReader() { return new StringReader(freshString()); } @Generates private Reader freshReader() { return freshStringReader(); } @Generates private Readable freshReadable() { return freshReader(); } @Generates private Buffer freshBuffer() { return freshCharBuffer(); } @Generates private CharBuffer freshCharBuffer() { return CharBuffer.allocate(freshInt()); } @Generates private ByteBuffer freshByteBuffer() { return ByteBuffer.allocate(freshInt()); } @Generates private ShortBuffer freshShortBuffer() { return ShortBuffer.allocate(freshInt()); } @Generates private IntBuffer freshIntBuffer() { return IntBuffer.allocate(freshInt()); } @Generates private LongBuffer freshLongBuffer() { return LongBuffer.allocate(freshInt()); } @Generates private FloatBuffer freshFloatBuffer() { return FloatBuffer.allocate(freshInt()); } @Generates private DoubleBuffer freshDoubleBuffer() { return DoubleBuffer.allocate(freshInt()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.logging.Level; import java.util.logging.Logger; /** * Simple utility for when you want to create a {@link TearDown} that may throw * an exception but should not fail a test when it does. (The behavior of a * {@code TearDown} that throws an exception varies; see its documentation for * details.) Use it just like a {@code TearDown}, except override {@link * #sloppyTearDown()} instead. * * @author Luiz-Otavio Zorzella * @since 10.0 */ @Beta @GwtCompatible public abstract class SloppyTearDown implements TearDown { public static final Logger logger = Logger.getLogger(SloppyTearDown.class.getName()); @Override public final void tearDown() { try { sloppyTearDown(); } catch (Throwable t) { logger.log(Level.INFO, "exception thrown during tearDown: " + t.getMessage(), t); } } public abstract void sloppyTearDown() throws Exception; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Ticker; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * A Ticker whose value can be advanced programmatically in test. * <p> * The ticker can be configured so that the time is incremented whenever {@link #read} is called: * see {@link #setAutoIncrementStep}. * <p> * This class is thread-safe. * * @author Jige Yu * @since 10.0 */ @Beta @GwtCompatible public class FakeTicker extends Ticker { private final AtomicLong nanos = new AtomicLong(); private volatile long autoIncrementStepNanos; /** Advances the ticker value by {@code time} in {@code timeUnit}. */ public FakeTicker advance(long time, TimeUnit timeUnit) { return advance(timeUnit.toNanos(time)); } /** Advances the ticker value by {@code nanoseconds}. */ public FakeTicker advance(long nanoseconds) { nanos.addAndGet(nanoseconds); return this; } /** * Sets the increment applied to the ticker whenever it is queried. * * <p>The default behavior is to auto increment by zero. i.e: The ticker is left unchanged when * queried. */ public FakeTicker setAutoIncrementStep(long autoIncrementStep, TimeUnit timeUnit) { checkArgument(autoIncrementStep >= 0, "May not auto-increment by a negative amount"); this.autoIncrementStepNanos = timeUnit.toNanos(autoIncrementStep); return this; } @Override public long read() { return nanos.getAndAdd(autoIncrementStepNanos); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * Any object which can accept registrations of {@link TearDown} instances. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible public interface TearDownAccepter { /** * Registers a TearDown implementor which will be run after the test proper. * * <p>In JUnit4 language, that means as an {@code @After}. * * <p>In JUnit3 language, that means during the * {@link junit.framework.TestCase#tearDown()} step. */ void addTearDown(TearDown tearDown); }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.Beta; import com.google.common.base.CharMatcher; import com.google.common.base.Charsets; import com.google.common.base.Defaults; import com.google.common.base.Equivalence; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.base.Ticker; import com.google.common.collect.BiMap; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMultiset; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Iterators; import com.google.common.collect.ListMultimap; import com.google.common.collect.MapConstraint; import com.google.common.collect.MapConstraints; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Multiset; import com.google.common.collect.Ordering; import com.google.common.collect.PeekingIterator; import com.google.common.collect.Range; import com.google.common.collect.RowSortedTable; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.collect.SortedMapDifference; import com.google.common.collect.SortedMultiset; import com.google.common.collect.SortedSetMultimap; import com.google.common.collect.Table; import com.google.common.collect.Tables; import com.google.common.collect.TreeBasedTable; import com.google.common.collect.TreeMultimap; import com.google.common.primitives.Primitives; import com.google.common.primitives.UnsignedInteger; import com.google.common.primitives.UnsignedLong; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.util.ArrayDeque; import java.util.Collection; import java.util.Comparator; import java.util.Currency; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.MatchResult; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Supplies an arbitrary "default" instance for a wide range of types, often useful in testing * utilities. * * <p>Covers common types defined in {@code java.lang}, {@code java.lang.reflect}, {@code java.io}, * {@code java.nio}, {@code java.math}, {@code java.util}, {@code java.util.concurrent}, * {@code java.util.regex}, {@code com.google.common.base}, {@code com.google.common.collect} * and {@code com.google.common.primitives}. In addition, any public class that exposes a public * parameter-less constructor will be "new"d and returned. * * <p>All default instances returned by {@link #get} are generics-safe. Clients won't get type * errors for using {@code get(Comparator.class)} as a {@code Comparator<Foo>}, for example. * Immutable empty instances are returned for collection types; {@code ""} for string; * {@code 0} for number types; reasonable default instance for other stateless types. For mutable * types, a fresh instance is created each time {@code get()} is called. * * @author Kevin Bourrillion * @author Ben Yu * @since 12.0 */ @Beta public final class ArbitraryInstances { private static final ClassToInstanceMap<Object> DEFAULTS = ImmutableClassToInstanceMap.builder() // primitives .put(Object.class, "") .put(Number.class, 0) .put(UnsignedInteger.class, UnsignedInteger.ZERO) .put(UnsignedLong.class, UnsignedLong.ZERO) .put(BigInteger.class, BigInteger.ZERO) .put(BigDecimal.class, BigDecimal.ZERO) .put(CharSequence.class, "") .put(String.class, "") .put(Pattern.class, Pattern.compile("")) .put(MatchResult.class, Pattern.compile("").matcher("").toMatchResult()) .put(TimeUnit.class, TimeUnit.SECONDS) .put(Charset.class, Charsets.UTF_8) .put(Currency.class, Currency.getInstance(Locale.US)) .put(Locale.class, Locale.US) // common.base .put(CharMatcher.class, CharMatcher.NONE) .put(Joiner.class, Joiner.on(',')) .put(Splitter.class, Splitter.on(',')) .put(Optional.class, Optional.absent()) .put(Predicate.class, Predicates.alwaysTrue()) .put(Equivalence.class, Equivalence.equals()) .put(Ticker.class, Ticker.systemTicker()) // io types .put(InputStream.class, new ByteArrayInputStream(new byte[0])) .put(ByteArrayInputStream.class, new ByteArrayInputStream(new byte[0])) .put(Readable.class, new StringReader("")) .put(Reader.class, new StringReader("")) .put(StringReader.class, new StringReader("")) .put(Buffer.class, ByteBuffer.allocate(0)) .put(CharBuffer.class, CharBuffer.allocate(0)) .put(ByteBuffer.class, ByteBuffer.allocate(0)) .put(ShortBuffer.class, ShortBuffer.allocate(0)) .put(IntBuffer.class, IntBuffer.allocate(0)) .put(LongBuffer.class, LongBuffer.allocate(0)) .put(FloatBuffer.class, FloatBuffer.allocate(0)) .put(DoubleBuffer.class, DoubleBuffer.allocate(0)) .put(File.class, new File("")) // All collections are immutable empty. So safe for any type parameter. .put(Iterator.class, Iterators.emptyIterator()) .put(PeekingIterator.class, Iterators.peekingIterator(Iterators.emptyIterator())) .put(ListIterator.class, ImmutableList.of().listIterator()) .put(Iterable.class, ImmutableSet.of()) .put(Collection.class, ImmutableList.of()) .put(ImmutableCollection.class, ImmutableList.of()) .put(List.class, ImmutableList.of()) .put(ImmutableList.class, ImmutableList.of()) .put(Set.class, ImmutableSet.of()) .put(ImmutableSet.class, ImmutableSet.of()) .put(SortedSet.class, ImmutableSortedSet.of()) .put(ImmutableSortedSet.class, ImmutableSortedSet.of()) .put(NavigableSet.class, Sets.unmodifiableNavigableSet(Sets.newTreeSet())) .put(Map.class, ImmutableMap.of()) .put(ImmutableMap.class, ImmutableMap.of()) .put(SortedMap.class, ImmutableSortedMap.of()) .put(ImmutableSortedMap.class, ImmutableSortedMap.of()) .put(NavigableMap.class, Maps.unmodifiableNavigableMap(Maps.newTreeMap())) .put(Multimap.class, ImmutableMultimap.of()) .put(ImmutableMultimap.class, ImmutableMultimap.of()) .put(ListMultimap.class, ImmutableListMultimap.of()) .put(ImmutableListMultimap.class, ImmutableListMultimap.of()) .put(SetMultimap.class, ImmutableSetMultimap.of()) .put(ImmutableSetMultimap.class, ImmutableSetMultimap.of()) .put(SortedSetMultimap.class, Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create())) .put(Multiset.class, ImmutableMultiset.of()) .put(ImmutableMultiset.class, ImmutableMultiset.of()) .put(SortedMultiset.class, ImmutableSortedMultiset.of()) .put(ImmutableSortedMultiset.class, ImmutableSortedMultiset.of()) .put(BiMap.class, ImmutableBiMap.of()) .put(ImmutableBiMap.class, ImmutableBiMap.of()) .put(Table.class, ImmutableTable.of()) .put(ImmutableTable.class, ImmutableTable.of()) .put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create())) .put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build()) .put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build()) .put(Comparable.class, ByToString.INSTANCE) .put(Comparator.class, AlwaysEqual.INSTANCE) .put(Ordering.class, AlwaysEqual.INSTANCE) .put(Range.class, Range.all()) .put(MapConstraint.class, MapConstraints.notNull()) .put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of())) .put(SortedMapDifference.class, Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of())) // reflect .put(AnnotatedElement.class, Object.class) .put(GenericDeclaration.class, Object.class) .put(Type.class, Object.class) .build(); /** * type -> implementation. Inherently mutable interfaces and abstract classes are mapped to their * default implementations and are "new"d upon get(). */ private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap(); private static <T> void setImplementation(Class<T> type, Class<? extends T> implementation) { checkArgument(type != implementation, "Don't register %s to itself!", type); checkArgument(!DEFAULTS.containsKey(type), "A default value was already registered for %s", type); checkArgument(implementations.put(type, implementation) == null, "Implementation for %s was already registered", type); } static { setImplementation(Appendable.class, StringBuilder.class); setImplementation(BlockingQueue.class, LinkedBlockingDeque.class); setImplementation(BlockingDeque.class, LinkedBlockingDeque.class); setImplementation(ConcurrentMap.class, ConcurrentHashMap.class); setImplementation(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class); setImplementation(CountDownLatch.class, Dummies.DummyCountDownLatch.class); setImplementation(Deque.class, ArrayDeque.class); setImplementation(OutputStream.class, ByteArrayOutputStream.class); setImplementation(PrintStream.class, Dummies.InMemoryPrintStream.class); setImplementation(PrintWriter.class, Dummies.InMemoryPrintWriter.class); setImplementation(Queue.class, ArrayDeque.class); setImplementation(Random.class, Dummies.DeterministicRandom.class); setImplementation(ScheduledThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class); setImplementation(ThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class); setImplementation(Writer.class, StringWriter.class); setImplementation(Runnable.class, Dummies.DummyRunnable.class); setImplementation(ThreadFactory.class, Dummies.DummyThreadFactory.class); setImplementation(Executor.class, Dummies.DummyExecutor.class); } @SuppressWarnings("unchecked") // it's a subtype map @Nullable private static <T> Class<? extends T> getImplementation(Class<T> type) { return (Class<? extends T>) implementations.get(type); } private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName()); /** * Returns an arbitrary value for {@code type} as the null value, or {@code null} if empty-ness is * unknown for the type. */ @Nullable public static <T> T get(Class<T> type) { T defaultValue = DEFAULTS.getInstance(type); if (defaultValue != null) { return defaultValue; } Class<? extends T> implementation = getImplementation(type); if (implementation != null) { return get(implementation); } if (type.isEnum()) { T[] enumConstants = type.getEnumConstants(); return (enumConstants.length == 0) ? null : enumConstants[0]; } if (type.isArray()) { return createEmptyArray(type); } T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type)); if (jvmDefault != null) { return jvmDefault; } if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) { return null; } final Constructor<T> constructor; try { constructor = type.getConstructor(); } catch (NoSuchMethodException e) { return null; } constructor.setAccessible(true); // accessibility check is too slow try { return constructor.newInstance(); } catch (InstantiationException impossible) { throw new AssertionError(impossible); } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); } catch (InvocationTargetException e) { logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause()); return null; } } @SuppressWarnings("unchecked") // same component type means same array type private static <T> T createEmptyArray(Class<T> arrayType) { return (T) Array.newInstance(arrayType.getComponentType(), 0); } // Internal implementations of some classes, with public default constructor that get() needs. private static final class Dummies { public static final class InMemoryPrintStream extends PrintStream { public InMemoryPrintStream() { super(new ByteArrayOutputStream()); } } public static final class InMemoryPrintWriter extends PrintWriter { public InMemoryPrintWriter() { super(new StringWriter()); } } public static final class DeterministicRandom extends Random { @SuppressWarnings("unused") // invoked by reflection public DeterministicRandom() { super(0); } } public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor { public DummyScheduledThreadPoolExecutor() { super(1); } } public static final class DummyCountDownLatch extends CountDownLatch { public DummyCountDownLatch() { super(0); } } public static final class DummyRunnable implements Runnable, Serializable { @Override public void run() {} } public static final class DummyThreadFactory implements ThreadFactory, Serializable { @Override public Thread newThread(Runnable r) { return new Thread(r); } } public static final class DummyExecutor implements Executor, Serializable { @Override public void execute(Runnable command) {} } } // Compare by toString() to satisfy 2 properties: // 1. compareTo(null) should throw NullPointerException // 2. the order is deterministic and easy to understand, for debugging purpose. private static final class ByToString implements Comparable<Object>, Serializable { private static final ByToString INSTANCE = new ByToString(); @Override public int compareTo(Object o) { return toString().compareTo(o.toString()); } @Override public String toString() { return "BY_TO_STRING"; } private Object readResolve() { return INSTANCE; } } // Always equal is a valid total ordering. And it works for any Object. private static final class AlwaysEqual extends Ordering<Object> implements Serializable { private static final AlwaysEqual INSTANCE = new AlwaysEqual(); @Override public int compare(Object o1, Object o2) { return 0; } @Override public String toString() { return "ALWAYS_EQUAL"; } private Object readResolve() { return INSTANCE; } } private ArbitraryInstances() {} }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.testing.RelationshipTester.RelationshipAssertion; import java.util.List; /** * Tester for equals() and hashCode() methods of a class. * * <p>To use, create a new EqualsTester and add equality groups where each group * contains objects that are supposed to be equal to each other, and objects of * different groups are expected to be unequal. For example: * <pre> * new EqualsTester() * .addEqualityGroup("hello", "h" + "ello") * .addEqualityGroup("world", "wor" + "ld") * .addEqualityGroup(2, 1 + 1) * .testEquals(); * </pre> * <p>This tests: * <ul> * <li>comparing each object against itself returns true * <li>comparing each object against null returns false * <li>comparing each object against an instance of an incompatible class * returns false * <li>comparing each pair of objects within the same equality group returns * true * <li>comparing each pair of objects from different equality groups returns * false * <li>the hash codes of any two equal objects are equal * </ul> * * <p>When a test fails, the error message labels the objects involved in * the failed comparison as follows: * <ul> * <li>"{@code [group }<i>i</i>{@code , item }<i>j</i>{@code ]}" refers to the * <i>j</i><sup>th</sup> item in the <i>i</i><sup>th</sup> equality group, * where both equality groups and the items within equality groups are * numbered starting from 1. When either a constructor argument or an * equal object is provided, that becomes group 1. * </ul> * * @author Jim McMaster * @author Jige Yu * @since 10.0 */ @Beta @GwtCompatible public final class EqualsTester { private static final int REPETITIONS = 3; private final List<List<Object>> equalityGroups = Lists.newArrayList(); private RelationshipTester.ItemReporter itemReporter = new RelationshipTester.ItemReporter(); /** * Constructs an empty EqualsTester instance */ public EqualsTester() {} /** * Adds {@code equalityGroup} with objects that are supposed to be equal to * each other and not equal to any other equality groups added to this tester. */ public EqualsTester addEqualityGroup(Object... equalityGroup) { checkNotNull(equalityGroup); equalityGroups.add(ImmutableList.copyOf(equalityGroup)); return this; } /** * Run tests on equals method, throwing a failure on an invalid test */ public EqualsTester testEquals() { RelationshipTester<Object> delegate = new RelationshipTester<Object>( new RelationshipAssertion<Object>() { @Override public void assertRelated(Object item, Object related) { assertEquals("$ITEM must be Object#equals to $RELATED", item, related); int itemHash = item.hashCode(); int relatedHash = related.hashCode(); assertEquals("the Object#hashCode (" + itemHash + ") of $ITEM must be equal to the " + "Object#hashCode (" + relatedHash +") of $RELATED", itemHash, relatedHash); } @Override public void assertUnrelated(Object item, Object unrelated) { // TODO(cpovirk): should this implementation (and // RelationshipAssertions in general) accept null inputs? assertTrue("$ITEM must not be Object#equals to $UNRELATED", !Objects.equal(item, unrelated)); } }, itemReporter); for (List<Object> group : equalityGroups) { delegate.addRelatedGroup(group); } for (int run = 0; run < REPETITIONS; run++) { testItems(); delegate.test(); } return this; } EqualsTester setItemReporter(RelationshipTester.ItemReporter reporter) { this.itemReporter = checkNotNull(reporter); return this; } private void testItems() { for (Object item : Iterables.concat(equalityGroups)) { assertTrue(item + " must not be Object#equals to null", !item.equals(null)); assertTrue(item + " must not be Object#equals to an arbitrary object of another class", !item.equals(NotAnInstance.EQUAL_TO_NOTHING)); assertEquals(item + " must be Object#equals to itself", item, item); assertEquals("the Object#hashCode of " + item + " must be consistent", item.hashCode(), item.hashCode()); } } /** * Class used to test whether equals() correctly handles an instance * of an incompatible class. Since it is a private inner class, the * invoker can never pass in an instance to the tester */ private enum NotAnInstance { EQUAL_TO_NOTHING; } }
Java
/* * Copyright (C) 2005 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.base.Objects; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.MutableClassToInstanceMap; import com.google.common.reflect.Invokable; import com.google.common.reflect.Parameter; import com.google.common.reflect.Reflection; import com.google.common.reflect.TypeToken; import junit.framework.Assert; import junit.framework.AssertionFailedError; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; /** * A test utility that verifies that your methods and constructors throw {@link * NullPointerException} or {@link UnsupportedOperationException} whenever null * is passed to a parameter that isn't annotated with {@link Nullable}. * * <p>The tested methods and constructors are invoked -- each time with one * parameter being null and the rest not null -- and the test fails if no * expected exception is thrown. {@code NullPointerTester} uses best effort to * pick non-null default values for many common JDK and Guava types, and also * for interfaces and public classes that have public parameter-less * constructors. When the non-null default value for a particular parameter type * cannot be provided by {@code NullPointerTester}, the caller can provide a * custom non-null default value for the parameter type via {@link #setDefault}. * * @author Kevin Bourrillion * @since 10.0 */ @Beta public final class NullPointerTester { private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create(); private final List<Member> ignoredMembers = Lists.newArrayList(); private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE; /** * Sets a default value that can be used for any parameter of type * {@code type}. Returns this object. */ public <T> NullPointerTester setDefault(Class<T> type, T value) { defaults.putInstance(type, checkNotNull(value)); return this; } /** * Ignore {@code method} in the tests that follow. Returns this object. * * @since 13.0 */ public NullPointerTester ignore(Method method) { ignoredMembers.add(checkNotNull(method)); return this; } /** * Runs {@link #testConstructor} on every constructor in class {@code c} that * has at least {@code minimalVisibility}. */ public void testConstructors(Class<?> c, Visibility minimalVisibility) { for (Constructor<?> constructor : c.getDeclaredConstructors()) { if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) { testConstructor(constructor); } } } /** * Runs {@link #testConstructor} on every public constructor in class {@code * c}. */ public void testAllPublicConstructors(Class<?> c) { testConstructors(c, Visibility.PUBLIC); } /** * Runs {@link #testMethod} on every static method of class {@code c} that has * at least {@code minimalVisibility}, including those "inherited" from * superclasses of the same package. */ public void testStaticMethods(Class<?> c, Visibility minimalVisibility) { for (Method method : minimalVisibility.getStaticMethods(c)) { if (!isIgnored(method)) { testMethod(null, method); } } } /** * Runs {@link #testMethod} on every public static method of class {@code c}, * including those "inherited" from superclasses of the same package. */ public void testAllPublicStaticMethods(Class<?> c) { testStaticMethods(c, Visibility.PUBLIC); } /** * Runs {@link #testMethod} on every instance method of the class of * {@code instance} with at least {@code minimalVisibility}, including those * inherited from superclasses of the same package. */ public void testInstanceMethods(Object instance, Visibility minimalVisibility) { for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) { testMethod(instance, method); } } ImmutableList<Method> getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility) { ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Method method : minimalVisibility.getInstanceMethods(c)) { if (!isIgnored(method)) { builder.add(method); } } return builder.build(); } /** * Runs {@link #testMethod} on every public instance method of the class of * {@code instance}, including those inherited from superclasses of the same * package. */ public void testAllPublicInstanceMethods(Object instance) { testInstanceMethods(instance, Visibility.PUBLIC); } /** * Verifies that {@code method} produces a {@link NullPointerException} * or {@link UnsupportedOperationException} whenever <i>any</i> of its * non-{@link Nullable} parameters are null. * * @param instance the instance to invoke {@code method} on, or null if * {@code method} is static */ public void testMethod(@Nullable Object instance, Method method) { Class<?>[] types = method.getParameterTypes(); for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { testMethodParameter(instance, method, nullIndex); } } /** * Verifies that {@code ctor} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} whenever <i>any</i> of its * non-{@link Nullable} parameters are null. */ public void testConstructor(Constructor<?> ctor) { Class<?> declaringClass = ctor.getDeclaringClass(); checkArgument(Modifier.isStatic(declaringClass.getModifiers()) || declaringClass.getEnclosingClass() == null, "Cannot test constructor of non-static inner class: %s", declaringClass.getName()); Class<?>[] types = ctor.getParameterTypes(); for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { testConstructorParameter(ctor, nullIndex); } } /** * Verifies that {@code method} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. * * @param instance the instance to invoke {@code method} on, or null if * {@code method} is static */ public void testMethodParameter( @Nullable final Object instance, final Method method, int paramIndex) { method.setAccessible(true); testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass()); } /** * Verifies that {@code ctor} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. */ public void testConstructorParameter(Constructor<?> ctor, int paramIndex) { ctor.setAccessible(true); testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass()); } /** Visibility of any method or constructor. */ public enum Visibility { PACKAGE { @Override boolean isVisible(int modifiers) { return !Modifier.isPrivate(modifiers); } }, PROTECTED { @Override boolean isVisible(int modifiers) { return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers); } }, PUBLIC { @Override boolean isVisible(int modifiers) { return Modifier.isPublic(modifiers); } }; abstract boolean isVisible(int modifiers); /** * Returns {@code true} if {@code member} is visible under {@code this} * visibility. */ final boolean isVisible(Member member) { return isVisible(member.getModifiers()); } final Iterable<Method> getStaticMethods(Class<?> cls) { ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Method method : getVisibleMethods(cls)) { if (Invokable.from(method).isStatic()) { builder.add(method); } } return builder.build(); } final Iterable<Method> getInstanceMethods(Class<?> cls) { ConcurrentMap<Signature, Method> map = Maps.newConcurrentMap(); for (Method method : getVisibleMethods(cls)) { if (!Invokable.from(method).isStatic()) { map.putIfAbsent(new Signature(method), method); } } return map.values(); } private ImmutableList<Method> getVisibleMethods(Class<?> cls) { // Don't use cls.getPackage() because it does nasty things like reading // a file. String visiblePackage = Reflection.getPackageName(cls); ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Class<?> type : TypeToken.of(cls).getTypes().classes().rawTypes()) { if (!Reflection.getPackageName(type).equals(visiblePackage)) { break; } for (Method method : type.getDeclaredMethods()) { if (!method.isSynthetic() && isVisible(method)) { builder.add(method); } } } return builder.build(); } } // TODO(benyu): Use labs/reflect/Signature if it graduates. private static final class Signature { private final String name; private final ImmutableList<Class<?>> parameterTypes; Signature(Method method) { this(method.getName(), ImmutableList.copyOf(method.getParameterTypes())); } Signature(String name, ImmutableList<Class<?>> parameterTypes) { this.name = name; this.parameterTypes = parameterTypes; } @Override public boolean equals(Object obj) { if (obj instanceof Signature) { Signature that = (Signature) obj; return name.equals(that.name) && parameterTypes.equals(that.parameterTypes); } return false; } @Override public int hashCode() { return Objects.hashCode(name, parameterTypes); } } /** * Verifies that {@code invokable} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. * * @param instance the instance to invoke {@code invokable} on, or null if * {@code invokable} is static */ private void testParameter(Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) { if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) { return; // there's nothing to test } Object[] params = buildParamList(invokable, paramIndex); try { @SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong. Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable; unsafe.invoke(instance, params); Assert.fail("No exception thrown for parameter at index " + paramIndex + " from " + invokable + Arrays.toString(params) + " for " + testedClass); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (policy.isExpectedType(cause)) { return; } AssertionFailedError error = new AssertionFailedError( "wrong exception thrown from " + invokable + ": " + cause); error.initCause(cause); throw error; } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) { ImmutableList<Parameter> params = invokable.getParameters(); Object[] args = new Object[params.size()]; for (int i = 0; i < args.length; i++) { Parameter param = params.get(i); if (i != indexOfParamToSetToNull) { args[i] = getDefaultValue(param.getType()); Assert.assertTrue( "Can't find or create a sample instance for type '" + param.getType() + "'; please provide one using NullPointerTester.setDefault()", args[i] != null || isNullable(param)); } } return args; } private <T> T getDefaultValue(TypeToken<T> type) { // We assume that all defaults are generics-safe, even if they aren't, // we take the risk. @SuppressWarnings("unchecked") T defaultValue = (T) defaults.getInstance(type.getRawType()); if (defaultValue != null) { return defaultValue; } @SuppressWarnings("unchecked") // All arbitrary instances are generics-safe T arbitrary = (T) ArbitraryInstances.get(type.getRawType()); if (arbitrary != null) { return arbitrary; } if (type.getRawType() == Class.class) { // If parameter is Class<? extends Foo>, we return Foo.class @SuppressWarnings("unchecked") T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType(); return defaultClass; } if (type.getRawType() == TypeToken.class) { // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>. @SuppressWarnings("unchecked") T defaultType = (T) getFirstTypeParameter(type.getType()); return defaultType; } if (type.getRawType().isInterface()) { return newDefaultReturningProxy(type); } return null; } private static TypeToken<?> getFirstTypeParameter(Type type) { if (type instanceof ParameterizedType) { return TypeToken.of( ((ParameterizedType) type).getActualTypeArguments()[0]); } else { return TypeToken.of(Object.class); } } private <T> T newDefaultReturningProxy(final TypeToken<T> type) { return new DummyProxy() { @Override <R> R dummyReturnValue(TypeToken<R> returnType) { return getDefaultValue(returnType); } }.newProxy(type); } private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) { if (instance == null) { return Invokable.from(method); } else { return TypeToken.of(instance.getClass()).method(method); } } static boolean isPrimitiveOrNullable(Parameter param) { return param.getType().getRawType().isPrimitive() || isNullable(param); } private static boolean isNullable(Parameter param) { return param.isAnnotationPresent(Nullable.class); } private boolean isIgnored(Member member) { return member.isSynthetic() || ignoredMembers.contains(member); } /** * Strategy for exception type matching used by {@link NullPointerTester}. */ private enum ExceptionTypePolicy { /** * Exceptions should be {@link NullPointerException} or * {@link UnsupportedOperationException}. */ NPE_OR_UOE() { @Override public boolean isExpectedType(Throwable cause) { return cause instanceof NullPointerException || cause instanceof UnsupportedOperationException; } }, /** * Exceptions should be {@link NullPointerException}, * {@link IllegalArgumentException}, or * {@link UnsupportedOperationException}. */ NPE_IAE_OR_UOE() { @Override public boolean isExpectedType(Throwable cause) { return cause instanceof NullPointerException || cause instanceof IllegalArgumentException || cause instanceof UnsupportedOperationException; } }; public abstract boolean isExpectedType(Throwable cause); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import com.google.common.annotations.GwtCompatible; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * An {@link ClusterException} is a data structure that allows for some code to * "throw multiple exceptions", or something close to it. The prototypical code * that calls for this class is presented below: * * <pre> * void runManyThings(List&lt;ThingToRun&gt; thingsToRun) { * for (ThingToRun thingToRun : thingsToRun) { * thingToRun.run(); // <-- say this may throw an exception, but you want to * // always run all thingsToRun * } * } * </pre> * * <p>This is what the code would become: * * <pre> * void runManyThings(List&lt;ThingToRun&gt; thingsToRun) { * List&lt;Exception&gt; exceptions = Lists.newArrayList(); * for (ThingToRun thingToRun : thingsToRun) { * try { * thingToRun.run(); * } catch (Exception e) { * exceptions.add(e); * } * } * if (exceptions.size() > 0) { * throw ClusterException.create(exceptions); * } * } * </pre> * * <p>See semantic details at {@link #create(Collection)}. * * @author Luiz-Otavio Zorzella */ @GwtCompatible final class ClusterException extends RuntimeException { public final Collection<? extends Throwable> exceptions; private ClusterException(Collection<? extends Throwable> exceptions) { super( exceptions.size() + " exceptions were thrown. The first exception is listed as a cause.", exceptions.iterator().next()); ArrayList<Throwable> temp = new ArrayList<Throwable>(); temp.addAll(exceptions); this.exceptions = Collections.unmodifiableCollection(temp); } /** * @see #create(Collection) */ public static RuntimeException create(Throwable... exceptions) { ArrayList<Throwable> temp = new ArrayList<Throwable>(); for (Throwable exception : exceptions) { temp.add(exception); } return create(temp); } /** * Given a collection of exceptions, returns a {@link RuntimeException}, with * the following rules: * * <ul> * <li>If {@code exceptions} has a single exception and that exception is a * {@link RuntimeException}, return it * <li>If {@code exceptions} has a single exceptions and that exceptions is * <em>not</em> a {@link RuntimeException}, return a simple * {@code RuntimeException} that wraps it * <li>Otherwise, return an instance of {@link ClusterException} that wraps * the first exception in the {@code exceptions} collection. * </ul> * * <p>Though this method takes any {@link Collection}, it often makes most * sense to pass a {@link java.util.List} or some other collection that * preserves the order in which the exceptions got added. * * @throws NullPointerException if {@code exceptions} is null * @throws IllegalArgumentException if {@code exceptions} is empty */ public static RuntimeException create(Collection<? extends Throwable> exceptions) { if (exceptions.size() == 0) { throw new IllegalArgumentException( "Can't create an ExceptionCollection with no exceptions"); } if (exceptions.size() == 1) { Throwable temp = exceptions.iterator().next(); if (temp instanceof RuntimeException) { return (RuntimeException)temp; } else { return new RuntimeException(temp); } } return new ClusterException(exceptions); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.reflect.AbstractInvocationHandler; import com.google.common.reflect.Invokable; import com.google.common.reflect.Parameter; import com.google.common.reflect.TypeToken; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Set; import javax.annotation.Nullable; /** * Generates a dummy interface proxy that simply returns a dummy value for each method. * * @author Ben Yu */ abstract class DummyProxy { /** * Returns a new proxy for {@code interfaceType}. Proxies of the same interface are equal to each * other if the {@link DummyProxy} instance that created the proxies are equal. */ final <T> T newProxy(TypeToken<T> interfaceType) { Set<Class<?>> interfaceClasses = Sets.newLinkedHashSet(); interfaceClasses.addAll(interfaceType.getTypes().interfaces().rawTypes()); // Make the proxy serializable to work with SerializableTester interfaceClasses.add(Serializable.class); Object dummy = Proxy.newProxyInstance( interfaceClasses.iterator().next().getClassLoader(), interfaceClasses.toArray(new Class<?>[interfaceClasses.size()]), new DummyHandler(interfaceType)); @SuppressWarnings("unchecked") // interfaceType is T T result = (T) dummy; return result; } /** Returns the dummy return value for {@code returnType}. */ abstract <R> R dummyReturnValue(TypeToken<R> returnType); private class DummyHandler extends AbstractInvocationHandler implements Serializable { private final TypeToken<?> interfaceType; DummyHandler(TypeToken<?> interfaceType) { this.interfaceType = interfaceType; } @Override protected Object handleInvocation( Object proxy, Method method, Object[] args) { Invokable<?, ?> invokable = interfaceType.method(method); ImmutableList<Parameter> params = invokable.getParameters(); for (int i = 0; i < args.length; i++) { Parameter param = params.get(i); if (!param.isAnnotationPresent(Nullable.class)) { checkNotNull(args[i]); } } return dummyReturnValue(interfaceType.resolveType(method.getGenericReturnType())); } @Override public int hashCode() { return identity().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof DummyHandler) { DummyHandler that = (DummyHandler) obj; return identity().equals(that.identity()); } else { return false; } } private DummyProxy identity() { return DummyProxy.this; } @Override public String toString() { return "Dummy proxy for " + interfaceType; } // Since type variables aren't serializable, reduce the type down to raw type before // serialization. private Object writeReplace() { return new DummyHandler(TypeToken.of(interfaceType.getRawType())); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; import junit.framework.TestCase; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Abstract test case parent for anything implementing {@link ListenableFuture}. * Tests the two get methods and the addListener method. * * @author Sven Mawson * @since 10.0 */ @Beta public abstract class AbstractListenableFutureTest extends TestCase { protected CountDownLatch latch; protected ListenableFuture<Boolean> future; @Override protected void setUp() throws Exception { // Create a latch and a future that waits on the latch. latch = new CountDownLatch(1); future = createListenableFuture(Boolean.TRUE, null, latch); } @Override protected void tearDown() throws Exception { // Make sure we have no waiting threads. latch.countDown(); } /** * Constructs a listenable future with a value available after the latch * has counted down. */ protected abstract <V> ListenableFuture<V> createListenableFuture( V value, Exception except, CountDownLatch waitOn); /** * Tests that the {@link Future#get()} method blocks until a value is * available. */ public void testGetBlocksUntilValueAvailable() throws Throwable { assertFalse(future.isDone()); assertFalse(future.isCancelled()); final CountDownLatch successLatch = new CountDownLatch(1); final Throwable[] badness = new Throwable[1]; // Wait on the future in a separate thread. new Thread(new Runnable() { @Override public void run() { try { assertSame(Boolean.TRUE, future.get()); successLatch.countDown(); } catch (Throwable t) { t.printStackTrace(); badness[0] = t; } }}).start(); // Release the future value. latch.countDown(); assertTrue(successLatch.await(10, TimeUnit.SECONDS)); if (badness[0] != null) { throw badness[0]; } assertTrue(future.isDone()); assertFalse(future.isCancelled()); } /** * Tests that the {@link Future#get(long, TimeUnit)} method times out * correctly. */ public void testTimeoutOnGetWorksCorrectly() throws InterruptedException, ExecutionException { // The task thread waits for the latch, so we expect a timeout here. try { future.get(20, TimeUnit.MILLISECONDS); fail("Should have timed out trying to get the value."); } catch (TimeoutException expected) { // Expected. } finally { latch.countDown(); } } /** * Tests that a canceled future throws a cancellation exception. * * This method checks the cancel, isCancelled, and isDone methods. */ public void testCanceledFutureThrowsCancellation() throws Exception { assertFalse(future.isDone()); assertFalse(future.isCancelled()); final CountDownLatch successLatch = new CountDownLatch(1); // Run cancellation in a separate thread as an extra thread-safety test. new Thread(new Runnable() { @Override public void run() { try { future.get(); } catch (CancellationException expected) { successLatch.countDown(); } catch (Exception ignored) { // All other errors are ignored, we expect a cancellation. } } }).start(); assertFalse(future.isDone()); assertFalse(future.isCancelled()); future.cancel(true); assertTrue(future.isDone()); assertTrue(future.isCancelled()); assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS)); latch.countDown(); } public void testListenersNotifiedOnError() throws Exception { final CountDownLatch successLatch = new CountDownLatch(1); final CountDownLatch listenerLatch = new CountDownLatch(1); ExecutorService exec = Executors.newCachedThreadPool(); future.addListener(new Runnable() { @Override public void run() { listenerLatch.countDown(); } }, exec); new Thread(new Runnable() { @Override public void run() { try { future.get(); } catch (CancellationException expected) { successLatch.countDown(); } catch (Exception ignored) { // No success latch count down. } } }).start(); future.cancel(true); assertTrue(future.isCancelled()); assertTrue(future.isDone()); assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS)); assertTrue(listenerLatch.await(200, TimeUnit.MILLISECONDS)); latch.countDown(); exec.shutdown(); exec.awaitTermination(100, TimeUnit.MILLISECONDS); } /** * Tests that all listeners complete, even if they were added before or after * the future was finishing. Also acts as a concurrency test to make sure the * locking is done correctly when a future is finishing so that no listeners * can be lost. */ public void testAllListenersCompleteSuccessfully() throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); int listenerCount = 20; final CountDownLatch listenerLatch = new CountDownLatch(listenerCount); // Test that listeners added both before and after the value is available // get called correctly. for (int i = 0; i < 20; i++) { // Right in the middle start up a thread to close the latch. if (i == 10) { new Thread(new Runnable() { @Override public void run() { latch.countDown(); } }).start(); } future.addListener(new Runnable() { @Override public void run() { listenerLatch.countDown(); } }, exec); } assertSame(Boolean.TRUE, future.get()); // Wait for the listener latch to complete. listenerLatch.await(500, TimeUnit.MILLISECONDS); exec.shutdown(); exec.awaitTermination(500, TimeUnit.MILLISECONDS); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import junit.framework.Assert; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * A simple mock implementation of {@code Runnable} that can be used for * testing ListenableFutures. * * @author Nishant Thakkar * @since 10.0 */ @Beta public class MockFutureListener implements Runnable { private final CountDownLatch countDownLatch; private final ListenableFuture<?> future; public MockFutureListener(ListenableFuture<?> future) { this.countDownLatch = new CountDownLatch(1); this.future = future; future.addListener(this, MoreExecutors.sameThreadExecutor()); } @Override public void run() { countDownLatch.countDown(); } /** * Verify that the listener completes in a reasonable amount of time, and * Asserts that the future returns the expected data. * @throws Throwable if the listener isn't called or if it resulted in a * throwable or if the result doesn't match the expected value. */ public void assertSuccess(Object expectedData) throws Throwable { // Verify that the listener executed in a reasonable amount of time. Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS)); try { Assert.assertEquals(expectedData, future.get()); } catch (ExecutionException e) { throw e.getCause(); } } /** * Verify that the listener completes in a reasonable amount of time, and * Asserts that the future throws an {@code ExecutableException} and that the * cause of the {@code ExecutableException} is {@code expectedCause}. */ public void assertException(Throwable expectedCause) throws Exception { // Verify that the listener executed in a reasonable amount of time. Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS)); try { future.get(); Assert.fail("This call was supposed to throw an ExecutionException"); } catch (ExecutionException expected) { Assert.assertSame(expectedCause, expected.getCause()); } } public void assertTimeout() throws Exception { // Verify that the listener does not get called in a reasonable amount of // time. Assert.assertFalse(countDownLatch.await(1L, TimeUnit.SECONDS)); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent.testing; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ForwardingListenableFuture.SimpleForwardingListenableFuture; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableScheduledFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import java.util.Collection; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.Callable; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A ScheduledExecutorService that executes all scheduled actions immediately * in the calling thread. * * See {@link TestingExecutors#sameThreadScheduledExecutor()} for a full list of * constraints. * * @author John Sirois * @author Zach van Schouwen */ class SameThreadScheduledExecutorService extends AbstractExecutorService implements ListeningScheduledExecutorService { private final ListeningExecutorService delegate = MoreExecutors.sameThreadExecutor(); @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(unit, "unit must not be null!"); return delegate.awaitTermination(timeout, unit); } @Override public <T> ListenableFuture<T> submit(Callable<T> task) { Preconditions.checkNotNull(task, "task must not be null!"); return delegate.submit(task); } @Override public <T> ListenableFuture<T> submit(Runnable task, T result) { Preconditions.checkNotNull(task, "task must not be null!"); Preconditions.checkNotNull(result, "result must not be null!"); return delegate.submit(task, result); } @Override public ListenableFuture<?> submit(Runnable task) { Preconditions.checkNotNull(task, "task must not be null!"); return delegate.submit(task); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { Preconditions.checkNotNull(tasks, "tasks must not be null!"); return delegate.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(tasks, "tasks must not be null!"); Preconditions.checkNotNull(unit, "unit must not be null!"); return delegate.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { Preconditions.checkNotNull(tasks, "tasks must not be null!"); return delegate.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Preconditions.checkNotNull(tasks, "tasks must not be null!"); Preconditions.checkNotNull(unit, "unit must not be null!"); return delegate.invokeAny(tasks, timeout, unit); } @Override public void execute(Runnable command) { Preconditions.checkNotNull(command, "command must not be null!"); delegate.execute(command); } @Override public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { Preconditions.checkNotNull(command, "command must not be null"); Preconditions.checkNotNull(unit, "unit must not be null!"); return schedule(java.util.concurrent.Executors.callable(command), delay, unit); } private static class ImmediateScheduledFuture<V> extends SimpleForwardingListenableFuture<V> implements ListenableScheduledFuture<V> { private ExecutionException exception; protected ImmediateScheduledFuture(ListenableFuture<V> future) { super(future); } @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Preconditions.checkNotNull(unit, "unit must not be null!"); return get(); } @Override public long getDelay(TimeUnit unit) { Preconditions.checkNotNull(unit, "unit must not be null!"); return 0; } @Override public int compareTo(Delayed other) { Preconditions.checkNotNull(other, "other must not be null!"); return 0; } } @Override public <V> ListenableScheduledFuture<V> schedule(final Callable<V> callable, long delay, TimeUnit unit) { Preconditions.checkNotNull(callable, "callable must not be null!"); Preconditions.checkNotNull(unit, "unit must not be null!"); ListenableFuture<V> delegateFuture = submit(callable); return new ImmediateScheduledFuture<V>(delegateFuture); } @Override public ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { throw new UnsupportedOperationException( "scheduleAtFixedRate is not supported."); } @Override public ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { throw new UnsupportedOperationException( "scheduleWithFixedDelay is not supported."); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Test case to make sure the {@link CheckedFuture#checkedGet()} and * {@link CheckedFuture#checkedGet(long, TimeUnit)} methods work correctly. * * @author Sven Mawson * @since 10.0 */ @Beta public abstract class AbstractCheckedFutureTest extends AbstractListenableFutureTest { /** * More specific type for the create method. */ protected abstract <V> CheckedFuture<V, ?> createCheckedFuture(V value, Exception except, CountDownLatch waitOn); /** * Checks that the exception is the correct type of cancellation exception. */ protected abstract void checkCancelledException(Exception e); /** * Checks that the exception is the correct type of execution exception. */ protected abstract void checkExecutionException(Exception e); /** * Checks that the exception is the correct type of interruption exception. */ protected abstract void checkInterruptedException(Exception e); @Override protected <V> ListenableFuture<V> createListenableFuture(V value, Exception except, CountDownLatch waitOn) { return createCheckedFuture(value, except, waitOn); } /** * Tests that the {@link CheckedFuture#checkedGet()} method throws the correct * type of cancellation exception when it is cancelled. */ public void testCheckedGetThrowsApplicationExceptionOnCancellation() { final CheckedFuture<Boolean, ?> future = createCheckedFuture(Boolean.TRUE, null, latch); assertFalse(future.isDone()); assertFalse(future.isCancelled()); new Thread(new Runnable() { @Override public void run() { future.cancel(true); } }).start(); try { future.checkedGet(); fail("RPC Should have been cancelled."); } catch (Exception e) { checkCancelledException(e); } assertTrue(future.isDone()); assertTrue(future.isCancelled()); } public void testCheckedGetThrowsApplicationExceptionOnInterruption() throws InterruptedException { final CheckedFuture<Boolean, ?> future = createCheckedFuture(Boolean.TRUE, null, latch); final CountDownLatch startingGate = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(1); assertFalse(future.isDone()); assertFalse(future.isCancelled()); Thread getThread = new Thread(new Runnable() { @Override public void run() { startingGate.countDown(); try { future.checkedGet(); } catch (Exception e) { checkInterruptedException(e); // This only gets hit if the original call throws an exception and // the check call above passes. successLatch.countDown(); } } }); getThread.start(); assertTrue(startingGate.await(500, TimeUnit.MILLISECONDS)); getThread.interrupt(); assertTrue(successLatch.await(500, TimeUnit.MILLISECONDS)); assertFalse(future.isDone()); assertFalse(future.isCancelled()); } public void testCheckedGetThrowsApplicationExceptionOnError() { final CheckedFuture<Boolean, ?> future = createCheckedFuture(Boolean.TRUE, new Exception("Error"), latch); assertFalse(future.isDone()); assertFalse(future.isCancelled()); new Thread(new Runnable() { @Override public void run() { latch.countDown(); } }).start(); try { future.checkedGet(); fail(); } catch (Exception e) { checkExecutionException(e); } assertTrue(future.isDone()); assertFalse(future.isCancelled()); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent.testing; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Longs; import com.google.common.util.concurrent.AbstractFuture; import com.google.common.util.concurrent.AbstractListeningExecutorService; import com.google.common.util.concurrent.ListenableScheduledFuture; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Delayed; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Factory methods for {@link ExecutorService} for testing. * * @author Chris Nokleberg * @since 14.0 */ @Beta public final class TestingExecutors { private TestingExecutors() {} /** * Returns a {@link ScheduledExecutorService} that never executes anything. * * <p>The {@code shutdownNow} method of the returned executor always returns an empty list despite * the fact that everything is still technically awaiting execution. * The {@code getDelay} method of any {@link ScheduledFuture} returned by the executor will always * return the max long value instead of the time until the user-specified delay. */ public static ListeningScheduledExecutorService noOpScheduledExecutor() { return new NoOpScheduledExecutorService(); } /** * Creates a scheduled executor service that runs each task in the thread * that invokes {@code execute/submit/schedule}, as in * {@link CallerRunsPolicy}. This applies both to individually submitted * tasks and to collections of tasks submitted via {@code invokeAll}, * {@code invokeAny}, {@code schedule}, {@code scheduleAtFixedRate}, and * {@code scheduleWithFixedDelay}. In the case of tasks submitted by * {@code invokeAll} or {@code invokeAny}, tasks will run serially on the * calling thread. Tasks are run to completion before a {@code Future} is * returned to the caller (unless the executor has been shutdown). * * <p>The returned executor is backed by the executor returned by * {@link MoreExecutors#sameThreadExecutor} and subject to the same * constraints. * * <p>Although all tasks are immediately executed in the thread that * submitted the task, this {@code ExecutorService} imposes a small * locking overhead on each task submission in order to implement shutdown * and termination behavior. * * <p>Because of the nature of single-thread execution, the methods * {@code scheduleAtFixedRate} and {@code scheduleWithFixedDelay} are not * supported by this class and will throw an UnsupportedOperationException. * * <p>The implementation deviates from the {@code ExecutorService} * specification with regards to the {@code shutdownNow} method. First, * "best-effort" with regards to canceling running tasks is implemented * as "no-effort". No interrupts or other attempts are made to stop * threads executing tasks. Second, the returned list will always be empty, * as any submitted task is considered to have started execution. * This applies also to tasks given to {@code invokeAll} or {@code invokeAny} * which are pending serial execution, even the subset of the tasks that * have not yet started execution. It is unclear from the * {@code ExecutorService} specification if these should be included, and * it's much easier to implement the interpretation that they not be. * Finally, a call to {@code shutdown} or {@code shutdownNow} may result * in concurrent calls to {@code invokeAll/invokeAny} throwing * RejectedExecutionException, although a subset of the tasks may already * have been executed. * * @since 15.0 */ public static SameThreadScheduledExecutorService sameThreadScheduledExecutor() { return new SameThreadScheduledExecutorService(); } private static final class NoOpScheduledExecutorService extends AbstractListeningExecutorService implements ListeningScheduledExecutorService { private volatile boolean shutdown; @Override public void shutdown() { shutdown = true; } @Override public List<Runnable> shutdownNow() { shutdown(); return ImmutableList.of(); } @Override public boolean isShutdown() { return shutdown; } @Override public boolean isTerminated() { return shutdown; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) { return true; } @Override public void execute(Runnable runnable) {} @Override public <V> ListenableScheduledFuture<V> schedule( Callable<V> callable, long delay, TimeUnit unit) { return NeverScheduledFuture.create(); } @Override public ListenableScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit) { return NeverScheduledFuture.create(); } @Override public ListenableScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit) { return NeverScheduledFuture.create(); } @Override public ListenableScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit) { return NeverScheduledFuture.create(); } private static class NeverScheduledFuture<V> extends AbstractFuture<V> implements ListenableScheduledFuture<V> { static <V> NeverScheduledFuture<V> create() { return new NeverScheduledFuture<V>(); } @Override public long getDelay(TimeUnit unit) { return Long.MAX_VALUE; } @Override public int compareTo(Delayed other) { return Longs.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS)); } } } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing.anotherpackage; /** Does not check null, but should not matter since it's in a different package. */ @SuppressWarnings("unused") // For use by NullPointerTester public class SomeClassThatDoesNotUseNullable { void packagePrivateButDoesNotCheckNull(String s) {} protected void protectedButDoesNotCheckNull(String s) {} public void publicButDoesNotCheckNull(String s) {} public static void staticButDoesNotCheckNull(String s) {} }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.ui.activity.LayoutGameActivity; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class XMLLayoutExample extends LayoutGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getLayoutID() { return R.layout.xmllayoutexample; } @Override protected int getRenderSurfaceViewID() { return R.id.xmllayoutexample_rendersurfaceview; } @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.animator.SlideMenuAnimator; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:33:33 - 01.04.2010 */ public class SubMenuExample extends MenuExample { // =========================================================== // Constants // =========================================================== private static final int MENU_QUIT_OK = MenuExample.MENU_QUIT + 1; private static final int MENU_QUIT_BACK = MENU_QUIT_OK + 1; // =========================================================== // Fields // =========================================================== private MenuScene mSubMenuScene; private BitmapTextureAtlas mSubMenuTexture; private TextureRegion mMenuOkTextureRegion; private TextureRegion mMenuBackTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onLoadResources() { super.onLoadResources(); this.mSubMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mMenuOkTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_ok.png", 0, 0); this.mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_back.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mSubMenuTexture); } @Override protected void createMenuScene() { super.createMenuScene(); this.mSubMenuScene = new MenuScene(this.mCamera); this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_OK, this.mMenuOkTextureRegion)); this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_BACK, this.mMenuBackTextureRegion)); this.mSubMenuScene.setMenuAnimator(new SlideMenuAnimator()); this.mSubMenuScene.buildAnimations(); this.mSubMenuScene.setBackgroundEnabled(false); this.mSubMenuScene.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: this.mMainScene.reset(); this.mMenuScene.back(); return true; case MENU_QUIT: pMenuScene.setChildSceneModal(this.mSubMenuScene); return true; case MENU_QUIT_BACK: this.mSubMenuScene.back(); return true; case MENU_QUIT_OK: this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class SpriteExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create the face and add it to the scene. */ final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import org.anddev.andengine.util.modifier.LoopModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class EntityModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Rectangle rect = new Rectangle(centerX + 100, centerY, 32, 32); rect.setColor(1, 0, 0); final AnimatedSprite face = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face.animate(100); face.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); final LoopEntityModifier entityModifier = new LoopEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence finished.", Toast.LENGTH_SHORT).show(); } }); } }, 2, new ILoopEntityModifierListener() { @Override public void onLoopStarted(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onLoopFinished(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' finished.", Toast.LENGTH_SHORT).show(); } }); } }, new SequenceEntityModifier( new RotationModifier(1, 0, 90), new AlphaModifier(2, 1, 0), new AlphaModifier(1, 0, 1), new ScaleModifier(2, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(3, 0.5f, 5), new RotationByModifier(3, 90) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ) ); face.registerEntityModifier(entityModifier); rect.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(face); scene.attachChild(rect); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class PathModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private RepeatingSpriteBackground mGrassBackground; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "You move my sprite right round, right round...", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png")); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { // this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); /* Create the face and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(10, 10, 48, 64, this.mPlayerTextureRegion); final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10); /* Add the proper animation when a waypoint of the path is passed. */ player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathStarted"); } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointStarted: " + pWaypointIndex); switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointFinished: " + pWaypointIndex); } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathFinished"); } }, EaseSineInOut.getInstance()))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:18:08 - 27.06.2010 */ public class PhysicsJumpExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 360; private static final int CAMERA_HEIGHT = 240; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private int mFaceCount = 0; private PhysicsWorld mPhysicsWorld; private float mGravityX; private float mGravityY; private Scene mScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects. Touch an object to shoot it up into the air.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); return this.mScene; } @Override public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final AnimatedSprite face = (AnimatedSprite) pTouchArea; this.jumpFace(face); return true; } return false; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { this.mGravityX = pAccelerometerData.getX(); this.mGravityY = pAccelerometerData.getY(); final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 1){ face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); face.animate(new long[]{200,200}, 0, 1, true); face.setUserData(body); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); } private void jumpFace(final AnimatedSprite face) { final Body faceBody = (Body)face.getUserData(); final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemSimpleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.TextMenuItem; import org.anddev.andengine.entity.scene.menu.item.decorator.ColorMenuItemDecorator; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 01:30:15 - 02.04.2010 */ public class TextMenuExample extends BaseExample implements IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected Scene mMainScene; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mFontTexture; private Font mFont; protected MenuScene mMenuScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* Load Font/Textures. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 48, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* Load Sprite-Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mMenuScene = this.createMenuScene(); /* Just a simple scene with an animated face flying around. */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mMainScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mMainScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mMainScene.reset(); /* Remove the menu and reset it. */ this.mMainScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected MenuScene createMenuScene() { final MenuScene menuScene = new MenuScene(this.mCamera); final IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_RESET, this.mFont, "RESET"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f); resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); menuScene.addMenuItem(resetMenuItem); final IMenuItem quitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_QUIT, this.mFont, "QUIT"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f); quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); menuScene.addMenuItem(quitMenuItem); menuScene.buildAnimations(); menuScene.setBackgroundEnabled(false); menuScene.setOnMenuItemClickListener(this); return menuScene; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 13.07.2011 */ public class PVRTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTextureRGB565; private ITexture mTextureRGBA5551; private ITexture mTextureARGB4444; private ITexture mTextureRGBA888MipMaps; private TextureRegion mHouseNearestTextureRegion; private TextureRegion mHouseLinearTextureRegion; private TextureRegion mHouseMipMapsNearestTextureRegion; private TextureRegion mHouseMipMapsLinearTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The lower houses use MipMaps!", Toast.LENGTH_LONG); Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTextureRGB565 = new PVRTexture(PVRTextureFormat.RGB_565, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_rgb_565); } }; this.mTextureRGBA5551 = new PVRTexture(PVRTextureFormat.RGBA_5551, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_5551); } }; this.mTextureARGB4444 = new PVRTexture(PVRTextureFormat.RGBA_4444, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_4444); } }; this.mTextureRGBA888MipMaps = new PVRTexture(PVRTextureFormat.RGBA_8888, new TextureOptions(GL10.GL_LINEAR_MIPMAP_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_8888_mipmaps); } }; this.mHouseNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGB565, 0, 0, 512, 512, true); this.mHouseLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA5551, 0, 0, 512, 512, true); this.mHouseMipMapsNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureARGB4444, 0, 0, 512, 512, true); this.mHouseMipMapsLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA888MipMaps, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTextureRGB565, this.mTextureRGBA5551, this.mTextureARGB4444, this.mTextureRGBA888MipMaps); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = CAMERA_WIDTH / 2; final int centerY = CAMERA_HEIGHT / 2; final Entity container = new Entity(centerX, centerY); container.setScale(0.5f); container.attachChild(new Sprite(-512, -384, this.mHouseNearestTextureRegion)); container.attachChild(new Sprite(0, -384, this.mHouseLinearTextureRegion)); container.attachChild(new Sprite(-512, -128, this.mHouseMipMapsNearestTextureRegion)); container.attachChild(new Sprite(0, -128, this.mHouseMipMapsLinearTextureRegion)); scene.attachChild(container); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRTextureExample.this.mZoomState = ZoomState.IN; } else { PVRTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Also try tapping this AnalogOnScreenControl!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, 200, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { face.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f), new ScaleModifier(0.25f, 1.5f, 1))); } }); analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); analogOnScreenControl.getControlBase().setScaleCenter(0, 128); analogOnScreenControl.getControlBase().setScale(1.25f); analogOnScreenControl.getControlKnob().setScale(1.25f); analogOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(analogOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ZoomExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch and hold the scene and the camera will smoothly zoom in.\nRelease the scene it to zoom out again.", Toast.LENGTH_LONG).show(); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 10, 10, 1.0f); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the screen-center. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create some faces and add them to the scene. */ scene.attachChild(new Sprite(centerX - 25, centerY - 25, this.mFaceTextureRegion)); scene.attachChild(new Sprite(centerX + 25, centerY - 25, this.mFaceTextureRegion)); scene.attachChild(new Sprite(centerX, centerY + 25, this.mFaceTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: ZoomExample.this.mSmoothCamera.setZoomFactor(5.0f); break; case TouchEvent.ACTION_UP: ZoomExample.this.mSmoothCamera.setZoomFactor(1.0f); break; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class CoordinateConversionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Scene mScene; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The arrow will always point to the left eye of the face!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Create three lines that will form an arrow pointing to the eye. */ final Line arrowLineMain = new Line(0, 0, 0, 0, 3); final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3); final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3); arrowLineMain.setColor(1, 0, 0); arrowLineWingLeft.setColor(1, 0, 0); arrowLineWingRight.setColor(1, 0, 0); /* Create a face-sprite. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion){ @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); final float[] eyeCoordinates = this.convertLocalToSceneCoordinates(11, 13); final float eyeX = eyeCoordinates[VERTEX_INDEX_X]; final float eyeY = eyeCoordinates[VERTEX_INDEX_Y]; arrowLineMain.setPosition(eyeX, eyeY, eyeX, eyeY - 50); arrowLineWingLeft.setPosition(eyeX, eyeY, eyeX - 10, eyeY - 10); arrowLineWingRight.setPosition(eyeX, eyeY, eyeX + 10, eyeY - 10); } }; final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); face.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(3, 1, 1.75f), new ScaleModifier(3, 1.75f, 1)))); this.mScene.attachChild(face); this.mScene.attachChild(arrowLineMain); this.mScene.attachChild(arrowLineWingLeft); this.mScene.attachChild(arrowLineWingRight); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); this.mScene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.entity.util.ScreenCapture; import org.anddev.andengine.entity.util.ScreenCapture.IScreenCaptureCallback; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.util.FileUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ScreenCaptureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to capture it (screenshot).", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final ScreenCapture screenCapture = new ScreenCapture(); scene.setBackground(new ColorBackground(0, 0, 0)); /* Create three lines that will form an arrow pointing to the eye. */ final Line arrowLineMain = new Line(0, 0, 0, 0, 3); final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3); final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3); arrowLineMain.setColor(1, 0, 1); arrowLineWingLeft.setColor(1, 0, 1); arrowLineWingRight.setColor(1, 0, 1); scene.attachChild(arrowLineMain); scene.attachChild(arrowLineWingLeft); scene.attachChild(arrowLineWingRight); /* Create the rectangles. */ final Rectangle rect1 = this.makeColoredRectangle(-180, -180, 1, 0, 0); final Rectangle rect2 = this.makeColoredRectangle(0, -180, 0, 1, 0); final Rectangle rect3 = this.makeColoredRectangle(0, 0, 0, 0, 1); final Rectangle rect4 = this.makeColoredRectangle(-180, 0, 1, 1, 0); final Entity rectangleGroup = new Entity(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2); rectangleGroup.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier( new SequenceEntityModifier( new ScaleModifier(10, 1, 0.5f), new ScaleModifier(10, 0.5f, 1) ), new RotationModifier(20, 0, 360)) )); rectangleGroup.attachChild(rect1); rectangleGroup.attachChild(rect2); rectangleGroup.attachChild(rect3); rectangleGroup.attachChild(rect4); scene.attachChild(rectangleGroup); /* Attaching the ScreenCapture to the end. */ scene.attachChild(screenCapture); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { final int viewWidth = ScreenCaptureExample.this.mRenderSurfaceView.getWidth(); final int viewHeight = ScreenCaptureExample.this.mRenderSurfaceView.getHeight(); screenCapture.capture(viewWidth, viewHeight, FileUtils.getAbsolutePathOnExternalStorage(ScreenCaptureExample.this, "Screen_" + System.currentTimeMillis() + ".png"), new IScreenCaptureCallback() { @Override public void onScreenCaptured(final String pFilePath) { ScreenCaptureExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ScreenCaptureExample.this, "Screenshot: " + pFilePath + " taken!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onScreenCaptureFailed(final String pFilePath, final Exception pException) { ScreenCaptureExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ScreenCaptureExample.this, "FAILED capturing Screenshot: " + pFilePath + " !", Toast.LENGTH_SHORT).show(); } }); } }); } return true; } }); return scene; } private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) { final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180); coloredRect.setColor(pRed, pGreen, pBlue); final Rectangle subRectangle = new Rectangle(45, 45, 90, 90); subRectangle.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360))); coloredRect.attachChild(subRectangle); return coloredRect; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class MovingBallExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final float DEMO_VELOCITY = 100.0f; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Ball ball = new Ball(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(ball); ball.registerUpdateHandler(physicsHandler); physicsHandler.setVelocity(DEMO_VELOCITY, DEMO_VELOCITY); scene.attachChild(ball); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== private static class Ball extends AnimatedSprite { private final PhysicsHandler mPhysicsHandler; public Ball(final float pX, final float pY, final TiledTextureRegion pTextureRegion) { super(pX, pY, pTextureRegion); this.mPhysicsHandler = new PhysicsHandler(this); this.registerUpdateHandler(this.mPhysicsHandler); } @Override protected void onManagedUpdate(final float pSecondsElapsed) { if(this.mX < 0) { this.mPhysicsHandler.setVelocityX(DEMO_VELOCITY); } else if(this.mX + this.getWidth() > CAMERA_WIDTH) { this.mPhysicsHandler.setVelocityX(-DEMO_VELOCITY); } if(this.mY < 0) { this.mPhysicsHandler.setVelocityY(DEMO_VELOCITY); } else if(this.mY + this.getHeight() > CAMERA_HEIGHT) { this.mPhysicsHandler.setVelocityY(-DEMO_VELOCITY); } super.onManagedUpdate(pSecondsElapsed); } } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.AutoParallaxBackground; import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 19:58:39 - 19.07.2010 */ public class AutoParallaxBackgroundExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; private TiledTextureRegion mEnemyTextureRegion; private BitmapTextureAtlas mAutoParallaxBackgroundTexture; private TextureRegion mParallaxLayerBack; private TextureRegion mParallaxLayerMid; private TextureRegion mParallaxLayerFront; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mEnemyTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "enemy.png", 73, 0, 3, 4); this.mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT); this.mParallaxLayerFront = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_front.png", 0, 0); this.mParallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_back.png", 0, 188); this.mParallaxLayerMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_mid.png", 0, 669); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mAutoParallaxBackgroundTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack))); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid))); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront))); scene.setBackground(autoParallaxBackground); /* Calculate the coordinates for the face, so its centered on the camera. */ final int playerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2; final int playerY = CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight() - 5; /* Create two sprits and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(playerX, playerY, this.mPlayerTextureRegion); player.setScaleCenterY(this.mPlayerTextureRegion.getTileHeight()); player.setScale(2); player.animate(new long[]{200, 200, 200}, 3, 5, true); final AnimatedSprite enemy = new AnimatedSprite(playerX - 80, playerY, this.mEnemyTextureRegion); enemy.setScaleCenterY(this.mEnemyTextureRegion.getTileHeight()); enemy.setScale(2); enemy.animate(new long[]{200, 200, 200}, 3, 5, true); scene.attachChild(player); scene.attachChild(enemy); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.app.cityradar; import java.util.ArrayList; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.examples.adt.cityradar.City; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureBuilder; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.sensor.location.ILocationListener; import org.anddev.andengine.sensor.location.LocationProviderStatus; import org.anddev.andengine.sensor.location.LocationSensorOptions; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationData; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.modifier.ease.EaseLinear; import android.graphics.Color; import android.graphics.Typeface; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; public class CityRadarActivity extends BaseGameActivity implements IOrientationListener, ILocationListener { // =========================================================== // Constants // =========================================================== private static final boolean USE_MOCK_LOCATION = false; private static final boolean USE_ACTUAL_LOCATION = !USE_MOCK_LOCATION; private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 800; private static final int GRID_SIZE = 80; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas; private TextureRegion mRadarPointTextureRegion; private TextureRegion mRadarTextureRegion; private BitmapTextureAtlas mFontTexture; private Font mFont; private Location mUserLocation; private final ArrayList<City> mCities = new ArrayList<City>(); private final HashMap<City, Sprite> mCityToCitySpriteMap = new HashMap<City, Sprite>(); private final HashMap<City, Text> mCityToCityNameTextMap = new HashMap<City, Text>(); private Scene mScene; // =========================================================== // Constructors // =========================================================== public CityRadarActivity() { this.mCities.add(new City("London", 51.509, -0.118)); this.mCities.add(new City("New York", 40.713, -74.006)); // this.mCities.add(new City("Paris", 48.857, 2.352)); this.mCities.add(new City("Beijing", 39.929, 116.388)); this.mCities.add(new City("Sydney", -33.850, 151.200)); this.mCities.add(new City("Berlin", 52.518, 13.408)); this.mCities.add(new City("Rio", -22.908, -43.196)); this.mCities.add(new City("New Delhi", 28.636, 77.224)); this.mCities.add(new City("Cape Town", -33.926, 18.424)); this.mUserLocation = new Location(LocationManager.GPS_PROVIDER); if(USE_MOCK_LOCATION) { this.mUserLocation.setLatitude(51.518); this.mUserLocation.setLongitude(13.408); } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public org.anddev.andengine.engine.Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CityRadarActivity.CAMERA_WIDTH, CityRadarActivity.CAMERA_HEIGHT); return new org.anddev.andengine.engine.Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new FillResolutionPolicy(), this.mCamera)); } @Override public void onLoadResources() { /* Init font. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.DEFAULT, 12, true, Color.WHITE); this.getFontManager().loadFont(this.mFont); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); /* Init TextureRegions. */ this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mRadarTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "radar.png"); this.mRadarPointTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "radarpoint.png"); try { this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1)); } catch (final TextureAtlasSourcePackingException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mScene = new Scene(); final HUD hud = new HUD(); this.mCamera.setHUD(hud); /* BACKGROUND */ this.initBackground(hud); /* CITIES */ this.initCitySprites(); return this.mScene; } private void initCitySprites() { final int cityCount = this.mCities.size(); for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final Sprite citySprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2, CityRadarActivity.CAMERA_HEIGHT / 2, this.mRadarPointTextureRegion); citySprite.setColor(0, 0.5f, 0, 1f); final Text cityNameText = new Text(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, this.mFont, city.getName()) { @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { /* This ensures that the name of the city is always 'pointing down'. */ this.setRotation(-CityRadarActivity.this.mCamera.getRotation()); super.onManagedDraw(pGL, pCamera); } }; cityNameText.setRotationCenterY(- citySprite.getHeight() / 2); this.mCityToCityNameTextMap.put(city, cityNameText); this.mCityToCitySpriteMap.put(city, citySprite); this.mScene.attachChild(citySprite); this.mScene.attachChild(cityNameText); } } private void initBackground(final IEntity pEntity) { /* Vertical Grid lines. */ for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_WIDTH; i += CityRadarActivity.GRID_SIZE) { final Line line = new Line(i, 0, i, CityRadarActivity.CAMERA_HEIGHT); line.setColor(0, 0.5f, 0, 1f); pEntity.attachChild(line); } /* Horizontal Grid lines. */ for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_HEIGHT; i += CityRadarActivity.GRID_SIZE) { final Line line = new Line(0, i, CityRadarActivity.CAMERA_WIDTH, i); line.setColor(0, 0.5f, 0, 1f); pEntity.attachChild(line); } /* Vertical Grid lines. */ final Sprite radarSprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2 - this.mRadarTextureRegion.getWidth(), CityRadarActivity.CAMERA_HEIGHT / 2 - this.mRadarTextureRegion.getHeight(), this.mRadarTextureRegion); radarSprite.setColor(0, 1f, 0, 1f); radarSprite.setRotationCenter(radarSprite.getWidth(), radarSprite.getHeight()); radarSprite.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360, EaseLinear.getInstance()))); pEntity.attachChild(radarSprite); /* Title. */ final Text titleText = new Text(0, 0, this.mFont, "-- CityRadar --"); titleText.setPosition(CAMERA_WIDTH / 2 - titleText.getWidth() / 2, titleText.getHeight() + 35); titleText.setScale(2); titleText.setScaleCenterY(0); pEntity.attachChild(titleText); } @Override public void onLoadComplete() { this.refreshCitySprites(); } @Override protected void onResume() { super.onResume(); this.enableOrientationSensor(this); final LocationSensorOptions locationSensorOptions = new LocationSensorOptions(); locationSensorOptions.setAccuracy(Criteria.ACCURACY_COARSE); locationSensorOptions.setMinimumTriggerTime(0); locationSensorOptions.setMinimumTriggerDistance(0); this.enableLocationSensor(this, locationSensorOptions); } @Override protected void onPause() { super.onPause(); this.mEngine.disableOrientationSensor(this); this.mEngine.disableLocationSensor(this); } @Override public void onOrientationChanged(final OrientationData pOrientationData) { this.mCamera.setRotation(-pOrientationData.getYaw()); } @Override public void onLocationChanged(final Location pLocation) { if(USE_ACTUAL_LOCATION) { this.mUserLocation = pLocation; } this.refreshCitySprites(); } @Override public void onLocationLost() { } @Override public void onLocationProviderDisabled() { } @Override public void onLocationProviderEnabled() { } @Override public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle) { } // =========================================================== // Methods // =========================================================== private void refreshCitySprites() { final double userLatitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLatitude()); final double userLongitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLongitude()); final int cityCount = this.mCities.size(); double maxDistance = Double.MIN_VALUE; /* Calculate the distances and bearings of the cities to the location of the user. */ for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final double cityLatitudeRad = MathUtils.degToRad((float) city.getLatitude()); final double cityLongitudeRad = MathUtils.degToRad((float) city.getLongitude()); city.setDistanceToUser(GeoMath.calculateDistance(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad)); city.setBearingToUser(GeoMath.calculateBearing(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad)); maxDistance = Math.max(maxDistance, city.getDistanceToUser()); } /* Calculate a scaleRatio so that all cities are visible at all times. */ final double scaleRatio = (CityRadarActivity.CAMERA_WIDTH / 2) / maxDistance * 0.93f; for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final Sprite citySprite = this.mCityToCitySpriteMap.get(city); final Text cityNameText = this.mCityToCityNameTextMap.get(city); final float bearingInRad = MathUtils.degToRad(90 - (float) city.getBearingToUser()); final float x = (float) (CityRadarActivity.CAMERA_WIDTH / 2 + city.getDistanceToUser() * scaleRatio * Math.cos(bearingInRad)); final float y = (float) (CityRadarActivity.CAMERA_HEIGHT / 2 - city.getDistanceToUser() * scaleRatio * Math.sin(bearingInRad)); citySprite.setPosition(x - citySprite.getWidth() / 2, y - citySprite.getHeight() / 2); final float textX = x - cityNameText.getWidth() / 2; final float textY = y + citySprite.getHeight() / 2; cityNameText.setPosition(textX, textY); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * Note: Formulas taken from <a href="http://www.movable-type.co.uk/scripts/latlong.html">here</a>. */ private static class GeoMath { // =========================================================== // Constants // =========================================================== private static final double RADIUS_EARTH_METERS = 6371000; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * @return the distance in meters. */ public static double calculateDistance(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) { return Math.acos(Math.sin(pLatitude1) * Math.sin(pLatitude2) + Math.cos(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1)) * RADIUS_EARTH_METERS; } /** * @return the bearing in degrees. */ public static double calculateBearing(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) { final double y = Math.sin(pLongitude2 - pLongitude1) * Math.cos(pLatitude2); final double x = Math.cos(pLatitude1) * Math.sin(pLatitude2) - Math.sin(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1); final float bearing = MathUtils.radToDeg((float) Math.atan2(y, x)); return (bearing + 360) % 360; } // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class SpriteRemoveExample extends BaseExample implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Sprite mFaceToRemove; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to safely remove the sprite.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFaceToRemove = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFaceToRemove); scene.setOnSceneTouchListener(this); return scene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { /* Removing entities can only be done safely on the UpdateThread. * Doing it while updating/drawing can * cause an exception with a suddenly missing entity. * Alternatively, there is a possibility to run the TouchEvents on the UpdateThread by default, by doing: * engineOptions.getTouchOptions().setRunOnUpdateThread(true); * when creating the Engine in onLoadEngine(); */ this.runOnUpdateThread(new Runnable() { @Override public void run() { /* Now it is save to remove the entity! */ pScene.detachChild(SpriteRemoveExample.this.mFaceToRemove); } }); return false; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake; import java.io.IOException; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.audio.sound.Sound; import org.anddev.andengine.audio.sound.SoundFactory; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.game.snake.adt.Direction; import org.anddev.andengine.examples.game.snake.adt.SnakeSuicideException; import org.anddev.andengine.examples.game.snake.entity.Frog; import org.anddev.andengine.examples.game.snake.entity.Snake; import org.anddev.andengine.examples.game.snake.entity.SnakeHead; import org.anddev.andengine.examples.game.snake.util.constants.SnakeConstants; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.HorizontalAlign; import org.anddev.andengine.util.MathUtils; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 02:26:05 - 08.07.2010 */ public class SnakeGameActivity extends BaseGameActivity implements SnakeConstants { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = CELLS_HORIZONTAL * CELL_WIDTH; // 640 private static final int CAMERA_HEIGHT = CELLS_VERTICAL * CELL_HEIGHT; // 480 private static final int LAYER_COUNT = 4; private static final int LAYER_BACKGROUND = 0; private static final int LAYER_FOOD = LAYER_BACKGROUND + 1; private static final int LAYER_SNAKE = LAYER_FOOD + 1; private static final int LAYER_SCORE = LAYER_SNAKE + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private DigitalOnScreenControl mDigitalOnScreenControl; private BitmapTextureAtlas mFontTexture; private Font mFont; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mTailPartTextureRegion; private TiledTextureRegion mHeadTextureRegion; private TiledTextureRegion mFrogTextureRegion; private BitmapTextureAtlas mBackgroundTexture; private TextureRegion mBackgroundTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private Scene mScene; private Snake mSnake; private Frog mFrog; private int mScore = 0; private ChangeableText mScoreText; private Sound mGameOverSound; private Sound mMunchSound; protected boolean mGameRunning; private Text mGameOverText; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera).setNeedsSound(true)); } @Override public void onLoadResources() { /* Load the font we are going to use. */ FontFactory.setAssetBasePath("font/"); this.mFontTexture = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 32, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* Load all the textures this game needs. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mHeadTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snake_head.png", 0, 0, 3, 1); this.mTailPartTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "snake_tailpart.png", 96, 0); this.mFrogTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "frog.png", 0, 64, 3, 1); this.mBackgroundTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.DEFAULT); this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBackgroundTexture, this, "snake_background.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBackgroundTexture, this.mBitmapTextureAtlas, this.mOnScreenControlTexture); /* Load all the sounds this game needs. */ try { SoundFactory.setAssetBasePath("mfx/"); this.mGameOverSound = SoundFactory.createSoundFromAsset(this.getSoundManager(), this, "game_over.ogg"); this.mMunchSound = SoundFactory.createSoundFromAsset(this.getSoundManager(), this, "munch.ogg"); } catch (final IOException e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); for(int i = 0; i < LAYER_COUNT; i++) { this.mScene.attachChild(new Entity()); } /* No background color needed as we have a fullscreen background sprite. */ this.mScene.setBackgroundEnabled(false); this.mScene.getChild(LAYER_BACKGROUND).attachChild(new Sprite(0, 0, this.mBackgroundTextureRegion)); /* The ScoreText showing how many points the pEntity scored. */ this.mScoreText = new ChangeableText(5, 5, this.mFont, "Score: 0", "Score: XXXX".length()); this.mScoreText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mScoreText.setAlpha(0.5f); this.mScene.getChild(LAYER_SCORE).attachChild(this.mScoreText); /* The Snake. */ this.mSnake = new Snake(Direction.RIGHT, 0, CELLS_VERTICAL / 2, this.mHeadTextureRegion, this.mTailPartTextureRegion); this.mSnake.getHead().animate(200); /* Snake starts with one tail. */ this.mSnake.grow(); this.mScene.getChild(LAYER_SNAKE).attachChild(this.mSnake); /* A frog to approach and eat. */ this.mFrog = new Frog(0, 0, this.mFrogTextureRegion); this.mFrog.animate(1000); this.setFrogToRandomCell(); this.mScene.getChild(LAYER_FOOD).attachChild(this.mFrog); /* The On-Screen Controls to control the direction of the snake. */ this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == 1) { SnakeGameActivity.this.mSnake.setDirection(Direction.RIGHT); } else if(pValueX == -1) { SnakeGameActivity.this.mSnake.setDirection(Direction.LEFT); } else if(pValueY == 1) { SnakeGameActivity.this.mSnake.setDirection(Direction.DOWN); } else if(pValueY == -1) { SnakeGameActivity.this.mSnake.setDirection(Direction.UP); } } }); /* Make the controls semi-transparent. */ this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f); this.mScene.setChildScene(this.mDigitalOnScreenControl); /* Make the Snake move every 0.5 seconds. */ this.mScene.registerUpdateHandler(new TimerHandler(0.5f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { if(SnakeGameActivity.this.mGameRunning) { try { SnakeGameActivity.this.mSnake.move(); } catch (final SnakeSuicideException e) { SnakeGameActivity.this.onGameOver(); } SnakeGameActivity.this.handleNewSnakePosition(); } } })); /* The title-text. */ final Text titleText = new Text(0, 0, this.mFont, "Snake\non a Phone!", HorizontalAlign.CENTER); titleText.setPosition((CAMERA_WIDTH - titleText.getWidth()) * 0.5f, (CAMERA_HEIGHT - titleText.getHeight()) * 0.5f); titleText.setScale(0.0f); titleText.registerEntityModifier(new ScaleModifier(2, 0.0f, 1.0f)); this.mScene.getChild(LAYER_SCORE).attachChild(titleText); /* The handler that removes the title-text and starts the game. */ this.mScene.registerUpdateHandler(new TimerHandler(3.0f, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { SnakeGameActivity.this.mScene.unregisterUpdateHandler(pTimerHandler); SnakeGameActivity.this.mScene.getChild(LAYER_SCORE).detachChild(titleText); SnakeGameActivity.this.mGameRunning = true; } })); /* The game-over text. */ this.mGameOverText = new Text(0, 0, this.mFont, "Game\nOver", HorizontalAlign.CENTER); this.mGameOverText.setPosition((CAMERA_WIDTH - this.mGameOverText.getWidth()) * 0.5f, (CAMERA_HEIGHT - this.mGameOverText.getHeight()) * 0.5f); this.mGameOverText.registerEntityModifier(new ScaleModifier(3, 0.1f, 2.0f)); this.mGameOverText.registerEntityModifier(new RotationModifier(3, 0, 720)); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void setFrogToRandomCell() { this.mFrog.setCell(MathUtils.random(1, CELLS_HORIZONTAL - 2), MathUtils.random(1, CELLS_VERTICAL - 2)); } private void handleNewSnakePosition() { final SnakeHead snakeHead = this.mSnake.getHead(); if(snakeHead.getCellX() < 0 || snakeHead.getCellX() >= CELLS_HORIZONTAL || snakeHead.getCellY() < 0 || snakeHead.getCellY() >= CELLS_VERTICAL) { this.onGameOver(); } else if(snakeHead.isInSameCell(this.mFrog)) { this.mScore += 50; this.mScoreText.setText("Score: " + this.mScore); this.mSnake.grow(); this.mMunchSound.play(); this.setFrogToRandomCell(); } } private void onGameOver() { this.mGameOverSound.play(); this.mScene.getChild(LAYER_SCORE).attachChild(this.mGameOverText); this.mGameRunning = false; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.examples.game.snake.util.constants.SnakeConstants; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:13:44 - 09.07.2010 */ public abstract class AnimatedCellEntity extends AnimatedSprite implements SnakeConstants, ICellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected int mCellX; protected int mCellY; // =========================================================== // Constructors // =========================================================== public AnimatedCellEntity(final int pCellX, final int pCellY, final int pWidth, final int pHeight, final TiledTextureRegion pTiledTextureRegion) { super(pCellX * CELL_WIDTH, pCellY * CELL_HEIGHT, pWidth, pHeight, pTiledTextureRegion); this.mCellX = pCellX; this.mCellY = pCellY; } // =========================================================== // Getter & Setter // =========================================================== public int getCellX() { return this.mCellX; } public int getCellY() { return this.mCellY; } public void setCell(final ICellEntity pCellEntity) { this.setCell(pCellEntity.getCellX(), pCellEntity.getCellY()); } public void setCell(final int pCellX, final int pCellY) { this.mCellX = pCellX; this.mCellY = pCellY; this.setPosition(this.mCellX * CELL_WIDTH, this.mCellY * CELL_HEIGHT); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public boolean isInSameCell(final ICellEntity pCellEntity) { return this.mCellX == pCellEntity.getCellX() && this.mCellY == pCellEntity.getCellY(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:08:58 - 11.07.2010 */ public class Frog extends AnimatedCellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public Frog(final int pCellX, final int pCellY, final TiledTextureRegion pTiledTextureRegion) { super(pCellX, pCellY, CELL_WIDTH, CELL_HEIGHT, pTiledTextureRegion); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.examples.game.snake.adt.Direction; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:44:59 - 09.07.2010 */ public class SnakeHead extends AnimatedCellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SnakeHead(final int pCellX, final int pCellY, final TiledTextureRegion pTiledTextureRegion) { super(pCellX, pCellY, CELL_WIDTH, 2 * CELL_HEIGHT, pTiledTextureRegion); this.setRotationCenterY(CELL_HEIGHT / 2); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void setRotation(final Direction pDirection) { switch(pDirection) { case UP: this.setRotation(180); break; case DOWN: this.setRotation(0); break; case LEFT: this.setRotation(90); break; case RIGHT: this.setRotation(270); break; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:44:59 - 09.07.2010 */ public class SnakeTailPart extends CellEntity implements Cloneable { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SnakeTailPart(final SnakeHead pSnakeHead, final TextureRegion pTextureRegion) { this(pSnakeHead.mCellX, pSnakeHead.mCellY, pTextureRegion); } public SnakeTailPart(final int pCellX, final int pCellY, final TextureRegion pTextureRegion) { super(pCellX, pCellY, CELL_WIDTH, CELL_HEIGHT, pTextureRegion); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected SnakeTailPart deepCopy() { return new SnakeTailPart(this.mCellX, this.mCellY, this.getTextureRegion()); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:39:05 - 11.07.2010 */ public interface ICellEntity { // =========================================================== // Constants // =========================================================== public abstract int getCellX(); public abstract int getCellY(); public abstract void setCell(final ICellEntity pCellEntity); public abstract void setCell(final int pCellX, final int pCellY); public abstract boolean isInSameCell(final ICellEntity pCellEntity); }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.examples.game.snake.util.constants.SnakeConstants; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:13:44 - 09.07.2010 */ public abstract class CellEntity extends Sprite implements SnakeConstants, ICellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected int mCellX; protected int mCellY; // =========================================================== // Constructors // =========================================================== public CellEntity(final int pCellX, final int pCellY, final int pWidth, final int pHeight, final TextureRegion pTextureRegion) { super(pCellX * CELL_WIDTH, pCellY * CELL_HEIGHT, pWidth, pHeight, pTextureRegion); this.mCellX = pCellX; this.mCellY = pCellY; } // =========================================================== // Getter & Setter // =========================================================== public int getCellX() { return this.mCellX; } public int getCellY() { return this.mCellY; } public void setCell(final ICellEntity pCellEntity) { this.setCell(pCellEntity.getCellX(), pCellEntity.getCellY()); } public void setCell(final int pCellX, final int pCellY) { this.mCellX = pCellX; this.mCellY = pCellY; this.setPosition(this.mCellX * CELL_WIDTH, this.mCellY * CELL_HEIGHT); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public boolean isInSameCell(final ICellEntity pCellEntity) { return this.mCellX == pCellEntity.getCellX() && this.mCellY == pCellEntity.getCellY(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import java.util.LinkedList; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.examples.game.snake.adt.Direction; import org.anddev.andengine.examples.game.snake.adt.SnakeSuicideException; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:11:44 - 09.07.2010 */ public class Snake extends Entity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final SnakeHead mHead; private final LinkedList<SnakeTailPart> mTail = new LinkedList<SnakeTailPart>(); private Direction mDirection; private boolean mGrow; private final TextureRegion mTailPartTextureRegion; private Direction mLastMoveDirection; // =========================================================== // Constructors // =========================================================== public Snake(final Direction pInitialDirection, final int pCellX, final int pCellY, final TiledTextureRegion pHeadTextureRegion, final TextureRegion pTailPartTextureRegion) { super(0, 0); this.mTailPartTextureRegion = pTailPartTextureRegion; this.mHead = new SnakeHead(pCellX, pCellY, pHeadTextureRegion); this.attachChild(this.mHead); this.setDirection(pInitialDirection); } // =========================================================== // Getter & Setter // =========================================================== public Direction getDirection() { return this.mDirection; } public void setDirection(final Direction pDirection) { if(this.mLastMoveDirection != Direction.opposite(pDirection)) { this.mDirection = pDirection; this.mHead.setRotation(pDirection); } } public int getTailLength() { return this.mTail.size(); } public SnakeHead getHead() { return this.mHead; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void grow() { this.mGrow = true; } public int getNextX() { return Direction.addToX(this.mDirection, this.mHead.getCellX()); } public int getNextY() { return Direction.addToY(this.mDirection, this.mHead.getCellY()); } public void move() throws SnakeSuicideException { this.mLastMoveDirection = this.mDirection; if(this.mGrow) { this.mGrow = false; /* If the snake should grow, * simply add a new part in the front of the tail, * where the head currently is. */ final SnakeTailPart newTailPart = new SnakeTailPart(this.mHead, this.mTailPartTextureRegion); this.attachChild(newTailPart); this.mTail.addFirst(newTailPart); } else { if(this.mTail.isEmpty() == false) { /* First move the end of the tail to where the head currently is. */ final SnakeTailPart tailEnd = this.mTail.removeLast(); tailEnd.setCell(this.mHead); this.mTail.addFirst(tailEnd); } } /* The move the head into the direction of the snake. */ this.mHead.setCell(this.getNextX(), this.getNextY()); /* Check if head collides with tail. */ for(int i = this.mTail.size() - 1; i >= 0; i--) { if(this.mHead.isInSameCell(this.mTail.get(i))) { throw new SnakeSuicideException(); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:29:05 - 08.07.2010 */ public enum Direction { // =========================================================== // Elements // =========================================================== UP, DOWN, LEFT, RIGHT; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static int addToX(final Direction pDirection, final int pX) { switch(pDirection) { case UP: case DOWN: return pX; case LEFT: return pX - 1; case RIGHT: return pX + 1; default: throw new IllegalArgumentException(); } } public static int addToY(final Direction pDirection, final int pY) { switch(pDirection) { case LEFT: case RIGHT: return pY; case UP: return pY - 1; case DOWN: return pY + 1; default: throw new IllegalArgumentException(); } } public static Direction opposite(final Direction pDirection) { switch(pDirection) { case UP: return DOWN; case DOWN: return UP; case LEFT: return RIGHT; case RIGHT: return LEFT; default: return null; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:29:42 - 11.07.2010 */ public class SnakeSuicideException extends Exception { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = -4008723747610431268L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:42:10 - 09.07.2010 */ public interface SnakeConstants { // =========================================================== // Final Fields // =========================================================== public static final int CELLS_HORIZONTAL = 16; public static final int CELLS_VERTICAL = 12; public static final int CELL_WIDTH = 32; public static final int CELL_HEIGHT = CELL_WIDTH; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong; import java.io.IOException; import java.util.ArrayList; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.examples.adt.messages.MessageConstants; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.client.ConnectionCloseClientMessage; import org.anddev.andengine.examples.adt.messages.client.ConnectionEstablishClientMessage; import org.anddev.andengine.examples.adt.messages.client.ConnectionPingClientMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionEstablishedServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionPongServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionRejectedProtocolMissmatchServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.game.pong.adt.PaddleUserData; import org.anddev.andengine.examples.game.pong.adt.Score; import org.anddev.andengine.examples.game.pong.adt.messages.client.MovePaddleClientMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.SetPaddleIDServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateBallServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdatePaddleServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateScoreServerMessage; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.IClientMessage; import org.anddev.andengine.extension.multiplayer.protocol.server.IClientMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener.DefaultSocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import android.util.SparseArray; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.Manifold; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:00:09 - 28.02.2011 */ public class PongServer extends SocketServer<SocketConnectionClientConnector> implements IUpdateHandler, PongConstants, ContactListener, ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== private static final FixtureDef PADDLE_FIXTUREDEF = PhysicsFactory.createFixtureDef(1, 1, 0); private static final FixtureDef BALL_FIXTUREDEF = PhysicsFactory.createFixtureDef(1, 1, 0); private static final FixtureDef WALL_FIXTUREDEF = PhysicsFactory.createFixtureDef(1, 1, 0); // =========================================================== // Fields // =========================================================== private final PhysicsWorld mPhysicsWorld; private final Body mBallBody; private final SparseArray<Body> mPaddleBodies = new SparseArray<Body>(); private boolean mResetBall = true; private final SparseArray<Score> mPaddleScores = new SparseArray<Score>(); private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private final ArrayList<UpdatePaddleServerMessage> mUpdatePaddleServerMessages = new ArrayList<UpdatePaddleServerMessage>(); // =========================================================== // Constructors // =========================================================== public PongServer(final ISocketConnectionClientConnectorListener pSocketConnectionClientConnectorListener) { super(SERVER_PORT, pSocketConnectionClientConnectorListener, new DefaultSocketServerListener<SocketConnectionClientConnector>()); this.initMessagePool(); this.mPaddleScores.put(PADDLE_LEFT.getOwnerID(), new Score()); this.mPaddleScores.put(PADDLE_RIGHT.getOwnerID(), new Score()); this.mPhysicsWorld = new FixedStepPhysicsWorld(FPS, 2, new Vector2(0, 0), false, 8, 8); this.mPhysicsWorld.setContactListener(this); /* Ball */ this.mBallBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, new Rectangle(-BALL_WIDTH_HALF, -BALL_HEIGHT_HALF, BALL_WIDTH, BALL_HEIGHT), BodyType.DynamicBody, BALL_FIXTUREDEF); this.mBallBody.setBullet(true); /* Paddles */ final Body paddleBodyLeft = PhysicsFactory.createBoxBody(this.mPhysicsWorld, new Rectangle(-GAME_WIDTH_HALF, -PADDLE_HEIGHT_HALF, PADDLE_WIDTH, PADDLE_HEIGHT), BodyType.KinematicBody, PADDLE_FIXTUREDEF); paddleBodyLeft.setUserData(PADDLE_LEFT); this.mPaddleBodies.put(PADDLE_LEFT.getOwnerID(), paddleBodyLeft); final Body paddleBodyRight = PhysicsFactory.createBoxBody(this.mPhysicsWorld, new Rectangle(GAME_WIDTH_HALF - PADDLE_WIDTH, -PADDLE_HEIGHT_HALF, PADDLE_WIDTH, PADDLE_HEIGHT), BodyType.KinematicBody, PADDLE_FIXTUREDEF); paddleBodyRight.setUserData(PADDLE_RIGHT); this.mPaddleBodies.put(PADDLE_RIGHT.getOwnerID(), paddleBodyRight); this.initWalls(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_CONNECTION_PONG, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_UPDATE_SCORE, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_UPDATE_BALL, UpdateBallServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_UPDATE_PADDLE, UpdatePaddleServerMessage.class); } private void initWalls() { final Line left = new Line(-GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, -GAME_WIDTH_HALF, GAME_HEIGHT_HALF); final Line right = new Line(GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF); WALL_FIXTUREDEF.isSensor = true; final Body leftBody = PhysicsFactory.createLineBody(this.mPhysicsWorld, left, WALL_FIXTUREDEF); leftBody.setUserData(this.mPaddleBodies.get(PADDLE_LEFT.getOwnerID())); final Body rightBody = PhysicsFactory.createLineBody(this.mPhysicsWorld, right, WALL_FIXTUREDEF); rightBody.setUserData(this.mPaddleBodies.get(PADDLE_RIGHT.getOwnerID())); WALL_FIXTUREDEF.isSensor = false; final Line top = new Line(-GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, GAME_WIDTH_HALF, -GAME_HEIGHT_HALF); final Line bottom = new Line(-GAME_WIDTH_HALF, GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF); PhysicsFactory.createLineBody(this.mPhysicsWorld, top, WALL_FIXTUREDEF); PhysicsFactory.createLineBody(this.mPhysicsWorld, bottom, WALL_FIXTUREDEF); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void preSolve(final Contact pContact, final Manifold pManifold) { } @Override public void postSolve(final Contact pContact, final ContactImpulse pContactImpulse) { } @Override public void beginContact(final Contact pContact) { final Fixture fixtureA = pContact.getFixtureA(); final Body bodyA = fixtureA.getBody(); final Object userDataA = bodyA.getUserData(); final Fixture fixtureB = pContact.getFixtureB(); final Body bodyB = fixtureB.getBody(); final Object userDataB = bodyB.getUserData(); final boolean isScoreSensorA = userDataA != null && userDataA instanceof Body; final boolean isScoreSensorB = userDataB != null && userDataB instanceof Body; if(isScoreSensorA || isScoreSensorB) { this.mResetBall = true; final PaddleUserData paddleUserData = (isScoreSensorA) ? (PaddleUserData)(((Body)userDataA).getUserData()) : (PaddleUserData)(((Body)userDataA).getUserData()); final int opponentID = paddleUserData.getOpponentID(); final Score opponentPaddleScore = this.mPaddleScores.get(opponentID); opponentPaddleScore.increase(); final UpdateScoreServerMessage updateScoreServerMessage = (UpdateScoreServerMessage)this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_UPDATE_SCORE); updateScoreServerMessage.set(opponentID, opponentPaddleScore.getScore()); final ArrayList<SocketConnectionClientConnector> clientConnectors = this.mClientConnectors; for(int i = 0; i < clientConnectors.size(); i++) { try { final ClientConnector<SocketConnection> clientConnector = clientConnectors.get(i); clientConnector.sendServerMessage(updateScoreServerMessage); } catch (final IOException e) { Debug.e(e); } } this.mMessagePool.recycleMessage(updateScoreServerMessage); } } @Override public void endContact(final Contact pContact) { } @Override public void onUpdate(final float pSecondsElapsed) { if(this.mResetBall) { this.mResetBall = false; final Vector2 vector2 = Vector2Pool.obtain(0, 0); this.mBallBody.setTransform(vector2, 0); vector2.set(MathUtils.randomSign() * MathUtils.random(3, 4), MathUtils.randomSign() * MathUtils.random(3, 4)); this.mBallBody.setLinearVelocity(vector2); Vector2Pool.recycle(vector2); } this.mPhysicsWorld.onUpdate(pSecondsElapsed); /* Prepare UpdateBallServerMessage. */ final Vector2 ballPosition = this.mBallBody.getPosition(); final float ballX = ballPosition.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BALL_WIDTH_HALF; final float ballY = ballPosition.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BALL_HEIGHT_HALF; final UpdateBallServerMessage updateBallServerMessage = (UpdateBallServerMessage)this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_UPDATE_BALL); updateBallServerMessage.set(ballX, ballY); final ArrayList<UpdatePaddleServerMessage> updatePaddleServerMessages = this.mUpdatePaddleServerMessages; /* Prepare UpdatePaddleServerMessages. */ final SparseArray<Body> paddleBodies = this.mPaddleBodies; for(int j = 0; j < paddleBodies.size(); j++) { final int paddleID = paddleBodies.keyAt(j); final Body paddleBody = paddleBodies.get(paddleID); final Vector2 paddlePosition = paddleBody.getPosition(); final float paddleX = paddlePosition.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - PADDLE_WIDTH_HALF; final float paddleY = paddlePosition.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - PADDLE_HEIGHT_HALF; final UpdatePaddleServerMessage updatePaddleServerMessage = (UpdatePaddleServerMessage)this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_UPDATE_PADDLE); updatePaddleServerMessage.set(paddleID, paddleX, paddleY); updatePaddleServerMessages.add(updatePaddleServerMessage); } try { /* Update Ball. */ this.sendBroadcastServerMessage(updateBallServerMessage); /* Update Paddles. */ for(int j = 0; j < updatePaddleServerMessages.size(); j++) { this.sendBroadcastServerMessage(updatePaddleServerMessages.get(j)); } this.sendBroadcastServerMessage(updateBallServerMessage); } catch (final IOException e) { Debug.e(e); } /* Recycle messages. */ this.mMessagePool.recycleMessage(updateBallServerMessage); this.mMessagePool.recycleMessages(updatePaddleServerMessages); updatePaddleServerMessages.clear(); } @Override public void reset() { /* Nothing. */ } @Override protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException { final SocketConnectionClientConnector clientConnector = new SocketConnectionClientConnector(pSocketConnection); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_MOVE_PADDLE, MovePaddleClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { final MovePaddleClientMessage movePaddleClientMessage = (MovePaddleClientMessage)pClientMessage; final Body paddleBody = PongServer.this.mPaddleBodies.get(movePaddleClientMessage.mPaddleID); final Vector2 paddlePosition = paddleBody.getTransform().getPosition(); final float paddleY = MathUtils.bringToBounds(-GAME_HEIGHT_HALF + PADDLE_HEIGHT_HALF, GAME_HEIGHT_HALF - PADDLE_HEIGHT_HALF, movePaddleClientMessage.mY); paddlePosition.set(paddlePosition.x, paddleY / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); paddleBody.setTransform(paddlePosition, 0); } }); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE, ConnectionCloseClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { pClientConnector.terminate(); } }); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH, ConnectionEstablishClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { final ConnectionEstablishClientMessage connectionEstablishClientMessage = (ConnectionEstablishClientMessage) pClientMessage; if(connectionEstablishClientMessage.getProtocolVersion() == MessageConstants.PROTOCOL_VERSION) { final ConnectionEstablishedServerMessage connectionEstablishedServerMessage = (ConnectionEstablishedServerMessage) PongServer.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED); try { pClientConnector.sendServerMessage(connectionEstablishedServerMessage); } catch (IOException e) { Debug.e(e); } PongServer.this.mMessagePool.recycleMessage(connectionEstablishedServerMessage); } else { final ConnectionRejectedProtocolMissmatchServerMessage connectionRejectedProtocolMissmatchServerMessage = (ConnectionRejectedProtocolMissmatchServerMessage) PongServer.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH); connectionRejectedProtocolMissmatchServerMessage.setProtocolVersion(MessageConstants.PROTOCOL_VERSION); try { pClientConnector.sendServerMessage(connectionRejectedProtocolMissmatchServerMessage); } catch (IOException e) { Debug.e(e); } PongServer.this.mMessagePool.recycleMessage(connectionRejectedProtocolMissmatchServerMessage); } } }); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_CONNECTION_PING, ConnectionPingClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { final ConnectionPongServerMessage connectionPongServerMessage = (ConnectionPongServerMessage) PongServer.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_CONNECTION_PONG); try { pClientConnector.sendServerMessage(connectionPongServerMessage); } catch (IOException e) { Debug.e(e); } PongServer.this.mMessagePool.recycleMessage(connectionPongServerMessage); } }); clientConnector.sendServerMessage(new SetPaddleIDServerMessage(this.mClientConnectors.size())); // TODO should not be size(), as it only works properly for first two connections! return clientConnector; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:27 - 28.02.2011 */ public class MovePaddleClientMessage extends ClientMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public float mY; // =========================================================== // Constructors // =========================================================== public MovePaddleClientMessage() { } public MovePaddleClientMessage(final int pID, final float pY) { this.mPaddleID = pID; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void setPaddleID(final int pPaddleID, final float pY) { this.mPaddleID = pPaddleID; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_MOVE_PADDLE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class SetPaddleIDServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; // =========================================================== // Constructors // =========================================================== public SetPaddleIDServerMessage() { } public SetPaddleIDServerMessage(final int pPaddleID) { this.mPaddleID = pPaddleID; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID) { this.mPaddleID = pPaddleID; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_SET_PADDLEID; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class UpdatePaddleServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public float mX; public float mY; // =========================================================== // Constructors // =========================================================== public UpdatePaddleServerMessage() { } public UpdatePaddleServerMessage(final int pPaddleID, final float pX, final float pY) { this.mPaddleID = pPaddleID; this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID, final float pX,final float pY) { this.mPaddleID = pPaddleID; this.mX = pX; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_PADDLE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class UpdateBallServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public float mX; public float mY; // =========================================================== // Constructors // =========================================================== public UpdateBallServerMessage() { } public UpdateBallServerMessage(final float pX, final float pY) { this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void set(final float pX,final float pY) { this.mX = pX; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_BALL; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:02:12 - 01.03.2011 */ public class UpdateScoreServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public int mScore; // =========================================================== // Constructors // =========================================================== public UpdateScoreServerMessage() { } public UpdateScoreServerMessage(final int pPaddleID, final int pScore) { this.mPaddleID = pPaddleID; this.mScore = pScore; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID, final int pScore) { this.mPaddleID = pPaddleID; this.mScore = pScore; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_SCORE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mScore = pDataInputStream.readInt(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeInt(this.mScore); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:11:58 - 01.03.2011 */ public class Score { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private int mScore = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public int getScore() { return this.mScore; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void increase() { this.mScore++; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:14:17 - 01.03.2011 */ public class PaddleUserData { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mOwnerID; private final int mOpponentID; // =========================================================== // Constructors // =========================================================== public PaddleUserData(final int pOwnerID, final int pOpponentID) { this.mOwnerID = pOwnerID; this.mOpponentID = pOpponentID; } // =========================================================== // Getter & Setter // =========================================================== public int getOwnerID() { return this.mOwnerID; } public int getOpponentID() { return this.mOpponentID; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.LimitedFPSEngine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.MessageConstants; import org.anddev.andengine.examples.adt.messages.client.ConnectionPingClientMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionEstablishedServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionPongServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionRejectedProtocolMissmatchServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.game.pong.adt.messages.client.MovePaddleClientMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.SetPaddleIDServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateBallServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdatePaddleServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateScoreServerMessage; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.Color; import android.util.SparseArray; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 19:36:45 - 28.02.2011 */ public class PongGameActivity extends BaseGameActivity implements PongConstants, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final String LOCALHOST_IP = "127.0.0.1"; private static final int CAMERA_WIDTH = GAME_WIDTH; private static final int CAMERA_HEIGHT = GAME_HEIGHT; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_ENTER_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_ENTER_SERVER_IP_ID + 1; private static final int PADDLEID_NOT_SET = -1; private static final int MENU_PING = Menu.FIRST; // =========================================================== // Fields // =========================================================== private Camera mCamera; private String mServerIP = LOCALHOST_IP; private int mPaddleID = PADDLEID_NOT_SET; private PongServer mServer; private PongServerConnector mServerConnector; private Rectangle mBall; private final SparseArray<Rectangle> mPaddleMap = new SparseArray<Rectangle>(); private final SparseArray<ChangeableText> mScoreChangeableTextMap = new SparseArray<ChangeableText>(); private BitmapTextureAtlas mScoreFontTexture; private Font mScoreFont; private float mPaddleCenterY; // =========================================================== // Constructors // =========================================================== @Override public Engine onLoadEngine() { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mCamera.setCenter(0,0); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new LimitedFPSEngine(engineOptions, FPS); } @Override public void onLoadResources() { this.mScoreFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mScoreFont = FontFactory.createFromAsset(this.mScoreFontTexture, this, "LCD.ttf", 32, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mScoreFontTexture); this.getFontManager().loadFont(this.mScoreFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); /* Ball */ this.mBall = new Rectangle(0, 0, BALL_WIDTH, BALL_HEIGHT); scene.attachChild(this.mBall); /* Walls */ scene.attachChild(new Line(-GAME_WIDTH_HALF + 1, -GAME_HEIGHT_HALF, -GAME_WIDTH_HALF + 1, GAME_HEIGHT_HALF)); // Left scene.attachChild(new Line(GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF)); // Right scene.attachChild(new Line(-GAME_WIDTH_HALF, -GAME_HEIGHT_HALF + 1, GAME_WIDTH_HALF , -GAME_HEIGHT_HALF + 1)); // Top scene.attachChild(new Line(-GAME_WIDTH_HALF, GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF)); // Bottom scene.attachChild(new Line(0, -GAME_HEIGHT_HALF, 0, GAME_HEIGHT_HALF)); // Middle /* Paddles */ final Rectangle paddleLeft = new Rectangle(0, 0, PADDLE_WIDTH, PADDLE_HEIGHT); final Rectangle paddleRight = new Rectangle(0, 0, PADDLE_WIDTH, PADDLE_HEIGHT); this.mPaddleMap.put(PADDLE_LEFT.getOwnerID(), paddleLeft); this.mPaddleMap.put(PADDLE_RIGHT.getOwnerID(), paddleRight); scene.attachChild(paddleLeft); scene.attachChild(paddleRight); /* Scores */ final ChangeableText scoreLeft = new ChangeableText(0, -GAME_HEIGHT_HALF + SCORE_PADDING, this.mScoreFont, "0", 2); scoreLeft.setPosition(-scoreLeft.getWidth() - SCORE_PADDING, scoreLeft.getY()); final ChangeableText scoreRight = new ChangeableText(SCORE_PADDING, -GAME_HEIGHT_HALF + SCORE_PADDING, this.mScoreFont, "0", 2); this.mScoreChangeableTextMap.put(PADDLE_LEFT.getOwnerID(), scoreLeft); this.mScoreChangeableTextMap.put(PADDLE_RIGHT.getOwnerID(), scoreRight); scene.attachChild(scoreLeft); scene.attachChild(scoreRight); scene.setOnSceneTouchListener(this); scene.registerUpdateHandler(new IUpdateHandler() { @Override public void onUpdate(final float pSecondsElapsed) { if(PongGameActivity.this.mPaddleID != PADDLEID_NOT_SET) { try { PongGameActivity.this.mServerConnector.sendClientMessage(new MovePaddleClientMessage(PongGameActivity.this.mPaddleID, PongGameActivity.this.mPaddleCenterY)); } catch (final IOException e) { Debug.e(e); } } } @Override public void reset() {} }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onCreateOptionsMenu(final Menu pMenu) { pMenu.add(Menu.NONE, MENU_PING, Menu.NONE, "Ping Server"); return super.onCreateOptionsMenu(pMenu); } @Override public boolean onMenuItemSelected(final int pFeatureId, final MenuItem pItem) { switch(pItem.getItemId()) { case MENU_PING: try { final ConnectionPingClientMessage connectionPingClientMessage = new ConnectionPingClientMessage(); // TODO Pooling connectionPingClientMessage.setTimestamp(System.currentTimeMillis()); this.mServerConnector.sendClientMessage(connectionPingClientMessage); } catch (final IOException e) { Debug.e(e); } return true; default: return super.onMenuItemSelected(pFeatureId, pItem); } } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: try { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("The IP of your Server is:\n" + WifiUtils.getWifiIPv4Address(this)) .setPositiveButton(android.R.string.ok, null) .create(); } catch (final UnknownHostException e) { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("Error retrieving IP of your Server: " + e) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.finish(); } }) .create(); } case DIALOG_ENTER_SERVER_IP_ID: final EditText ipEditText = new EditText(this); return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Enter Server-IP ...") .setCancelable(false) .setView(ipEditText) .setPositiveButton("Connect", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.mServerIP = ipEditText.getText().toString(); PongGameActivity.this.initClient(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.finish(); } }) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.showDialog(DIALOG_ENTER_SERVER_IP_ID); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.initServerAndClient(); PongGameActivity.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { this.mPaddleCenterY = pSceneTouchEvent.getY(); return true; } @Override protected void onDestroy() { if(this.mServer != null) { try { this.mServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== public void updateScore(final int pPaddleID, final int pPoints) { final ChangeableText scoreChangeableText = this.mScoreChangeableTextMap.get(pPaddleID); scoreChangeableText.setText(String.valueOf(pPoints)); /* Adjust position of left Score, so that it doesn't overlap the middle line. */ if(pPaddleID == PADDLE_LEFT.getOwnerID()) { scoreChangeableText.setPosition(-scoreChangeableText.getWidth() - SCORE_PADDING, scoreChangeableText.getY()); } } public void setPaddleID(final int pPaddleID) { this.mPaddleID = pPaddleID; } public void updatePaddle(final int pPaddleID, final float pX, final float pY) { this.mPaddleMap.get(pPaddleID).setPosition(pX, pY); } public void updateBall(final float pX, final float pY) { this.mBall.setPosition(pX, pY); } private void initServerAndClient() { PongGameActivity.this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } PongGameActivity.this.initClient(); } private void initServer() { this.mServer = new PongServer(new ExampleClientConnectorListener()); this.mServer.start(); this.mEngine.registerUpdateHandler(this.mServer); } private void initClient() { try { this.mServerConnector = new PongServerConnector(this.mServerIP, new ExampleServerConnectorListener()); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void toast(final String pMessage) { this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PongGameActivity.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== private class PongServerConnector extends ServerConnector<SocketConnection> implements PongConstants, ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public PongServerConnector(final String pServerIP, final ISocketConnectionServerConnectorListener pSocketConnectionServerConnectorListener) throws IOException { super(new SocketConnection(new Socket(pServerIP, SERVER_PORT)), pSocketConnectionServerConnectorListener); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { PongGameActivity.this.finish(); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED, ConnectionEstablishedServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { Debug.d("CLIENT: Connection established."); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH, ConnectionRejectedProtocolMissmatchServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final ConnectionRejectedProtocolMissmatchServerMessage connectionRejectedProtocolMissmatchServerMessage = (ConnectionRejectedProtocolMissmatchServerMessage)pServerMessage; if(connectionRejectedProtocolMissmatchServerMessage.getProtocolVersion() > MessageConstants.PROTOCOL_VERSION) { // Toast.makeText(context, text, duration).show(); } else if(connectionRejectedProtocolMissmatchServerMessage.getProtocolVersion() < MessageConstants.PROTOCOL_VERSION) { // Toast.makeText(context, text, duration).show(); } PongGameActivity.this.finish(); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_PONG, ConnectionPongServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final ConnectionPongServerMessage connectionPongServerMessage = (ConnectionPongServerMessage) pServerMessage; final long roundtripMilliseconds = System.currentTimeMillis() - connectionPongServerMessage.getTimestamp(); Debug.v("Ping: " + roundtripMilliseconds / 2 + "ms"); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_SET_PADDLEID, SetPaddleIDServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final SetPaddleIDServerMessage setPaddleIDServerMessage = (SetPaddleIDServerMessage) pServerMessage; PongGameActivity.this.setPaddleID(setPaddleIDServerMessage.mPaddleID); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_UPDATE_SCORE, UpdateScoreServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final UpdateScoreServerMessage updateScoreServerMessage = (UpdateScoreServerMessage) pServerMessage; PongGameActivity.this.updateScore(updateScoreServerMessage.mPaddleID, updateScoreServerMessage.mScore); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_UPDATE_BALL, UpdateBallServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final UpdateBallServerMessage updateBallServerMessage = (UpdateBallServerMessage) pServerMessage; PongGameActivity.this.updateBall(updateBallServerMessage.mX, updateBallServerMessage.mY); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_UPDATE_PADDLE, UpdatePaddleServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final UpdatePaddleServerMessage updatePaddleServerMessage = (UpdatePaddleServerMessage) pServerMessage; PongGameActivity.this.updatePaddle(updatePaddleServerMessage.mPaddleID, updatePaddleServerMessage.mX, updatePaddleServerMessage.mY); } }); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<SocketConnection> pServerConnector) { PongGameActivity.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<SocketConnection> pServerConnector) { PongGameActivity.this.toast("CLIENT: Disconnected from Server."); PongGameActivity.this.finish(); } } private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<SocketConnection> pClientConnector) { PongGameActivity.this.toast("SERVER: Client connected: " + pClientConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } @Override public void onTerminated(final ClientConnector<SocketConnection> pClientConnector) { PongGameActivity.this.toast("SERVER: Client disconnected: " + pClientConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } } }
Java
package org.anddev.andengine.examples.game.pong.util.constants; import org.anddev.andengine.examples.game.pong.adt.PaddleUserData; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:49:20 - 28.02.2011 */ public interface PongConstants { // =========================================================== // Final Fields // =========================================================== public static final int FPS = 30; public static final int GAME_WIDTH = 720; public static final int GAME_WIDTH_HALF = GAME_WIDTH / 2; public static final int GAME_HEIGHT = 480; public static final int GAME_HEIGHT_HALF = GAME_HEIGHT / 2; public static final int PADDLE_WIDTH = 20; public static final int PADDLE_WIDTH_HALF = PADDLE_WIDTH / 2; public static final int PADDLE_HEIGHT = 80; public static final int PADDLE_HEIGHT_HALF = PADDLE_HEIGHT / 2; public static final int BALL_WIDTH = 10; public static final int BALL_WIDTH_HALF = BALL_WIDTH / 2; public static final int BALL_HEIGHT = 10; public static final int BALL_HEIGHT_HALF = BALL_HEIGHT / 2; public static final int SCORE_PADDING = 5; public static final PaddleUserData PADDLE_LEFT = new PaddleUserData(0, 1); public static final PaddleUserData PADDLE_RIGHT = new PaddleUserData(1, 0); public static final int SERVER_PORT = 4444; /* Server --> Client */ public static final short FLAG_MESSAGE_SERVER_SET_PADDLEID = 1; public static final short FLAG_MESSAGE_SERVER_UPDATE_SCORE = FLAG_MESSAGE_SERVER_SET_PADDLEID + 1; public static final short FLAG_MESSAGE_SERVER_UPDATE_BALL = FLAG_MESSAGE_SERVER_UPDATE_SCORE + 1; public static final short FLAG_MESSAGE_SERVER_UPDATE_PADDLE = FLAG_MESSAGE_SERVER_UPDATE_BALL + 1; /* Client --> Server */ public static final short FLAG_MESSAGE_CLIENT_MOVE_PADDLE = 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.game.racer; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.TiledSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 22:43:20 - 15.07.2010 */ public class RacerGameActivity extends BaseGameActivity { // =========================================================== // Constants // =========================================================== private static final int RACETRACK_WIDTH = 64; private static final int OBSTACLE_SIZE = 16; private static final int CAR_SIZE = 16; private static final int CAMERA_WIDTH = RACETRACK_WIDTH * 5; private static final int CAMERA_HEIGHT = RACETRACK_WIDTH * 3; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mVehiclesTexture; private TiledTextureRegion mVehiclesTextureRegion; private BitmapTextureAtlas mBoxTexture; private TextureRegion mBoxTextureRegion; private BitmapTextureAtlas mRacetrackTexture; private TextureRegion mRacetrackStraightTextureRegion; private TextureRegion mRacetrackCurveTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private Body mCarBody; private TiledSprite mCar; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mVehiclesTexture = new BitmapTextureAtlas(128, 16, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mVehiclesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mVehiclesTexture, this, "vehicles.png", 0, 0, 6, 1); this.mRacetrackTexture = new BitmapTextureAtlas(128, 256, TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA); this.mRacetrackStraightTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mRacetrackTexture, this, "racetrack_straight.png", 0, 0); this.mRacetrackCurveTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mRacetrackTexture, this, "racetrack_curve.png", 0, 128); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mBoxTexture = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBoxTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBoxTexture, this, "box.png", 0, 0); this.mEngine.getTextureManager().loadTextures(this.mVehiclesTexture, this.mRacetrackTexture, this.mOnScreenControlTexture, this.mBoxTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0), false, 8, 1); this.initRacetrack(); this.initRacetrackBorders(); this.initCar(); this.initObstacles(); this.initOnScreenControls(); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void initOnScreenControls() { final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { final Body carBody = RacerGameActivity.this.mCarBody; final Vector2 velocity = Vector2Pool.obtain(pValueX * 5, pValueY * 5); carBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); final float rotationInRad = (float)Math.atan2(-pValueX, pValueY); carBody.setTransform(carBody.getWorldCenter(), rotationInRad); RacerGameActivity.this.mCar.setRotation(MathUtils.radToDeg(rotationInRad)); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); // analogOnScreenControl.getControlBase().setScaleCenter(0, 128); // analogOnScreenControl.getControlBase().setScale(0.75f); // analogOnScreenControl.getControlKnob().setScale(0.75f); analogOnScreenControl.refreshControlKnobPosition(); this.mScene.setChildScene(analogOnScreenControl); } private void initCar() { this.mCar = new TiledSprite(20, 20, CAR_SIZE, CAR_SIZE, this.mVehiclesTextureRegion); this.mCar.setCurrentTileIndex(0); final FixtureDef carFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); this.mCarBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, this.mCar, BodyType.DynamicBody, carFixtureDef); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(this.mCar, this.mCarBody, true, false)); this.mScene.attachChild(this.mCar); } private void initObstacles() { this.addObstacle(CAMERA_WIDTH / 2, RACETRACK_WIDTH / 2); this.addObstacle(CAMERA_WIDTH / 2, RACETRACK_WIDTH / 2); this.addObstacle(CAMERA_WIDTH / 2, CAMERA_HEIGHT - RACETRACK_WIDTH / 2); this.addObstacle(CAMERA_WIDTH / 2, CAMERA_HEIGHT - RACETRACK_WIDTH / 2); } private void addObstacle(final float pX, final float pY) { final Sprite box = new Sprite(pX, pY, OBSTACLE_SIZE, OBSTACLE_SIZE, this.mBoxTextureRegion); final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0.1f, 0.5f, 0.5f); final Body boxBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, box, BodyType.DynamicBody, boxFixtureDef); boxBody.setLinearDamping(10); boxBody.setAngularDamping(10); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(box, boxBody, true, true)); this.mScene.attachChild(box); } private void initRacetrack() { /* Straights. */ { final TextureRegion racetrackHorizontalStraightTextureRegion = this.mRacetrackStraightTextureRegion.deepCopy(); racetrackHorizontalStraightTextureRegion.setWidth(3 * this.mRacetrackStraightTextureRegion.getWidth()); final TextureRegion racetrackVerticalStraightTextureRegion = this.mRacetrackStraightTextureRegion; /* Top Straight */ this.mScene.attachChild(new Sprite(RACETRACK_WIDTH, 0, 3 * RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackHorizontalStraightTextureRegion)); /* Bottom Straight */ this.mScene.attachChild(new Sprite(RACETRACK_WIDTH, CAMERA_HEIGHT - RACETRACK_WIDTH, 3 * RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackHorizontalStraightTextureRegion)); /* Left Straight */ final Sprite leftVerticalStraight = new Sprite(0, RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackVerticalStraightTextureRegion); leftVerticalStraight.setRotation(90); this.mScene.attachChild(leftVerticalStraight); /* Right Straight */ final Sprite rightVerticalStraight = new Sprite(CAMERA_WIDTH - RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackVerticalStraightTextureRegion); rightVerticalStraight.setRotation(90); this.mScene.attachChild(rightVerticalStraight); } /* Edges */ { final TextureRegion racetrackCurveTextureRegion = this.mRacetrackCurveTextureRegion; /* Upper Left */ final Sprite upperLeftCurve = new Sprite(0, 0, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); upperLeftCurve.setRotation(90); this.mScene.attachChild(upperLeftCurve); /* Upper Right */ final Sprite upperRightCurve = new Sprite(CAMERA_WIDTH - RACETRACK_WIDTH, 0, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); upperRightCurve.setRotation(180); this.mScene.attachChild(upperRightCurve); /* Lower Right */ final Sprite lowerRightCurve = new Sprite(CAMERA_WIDTH - RACETRACK_WIDTH, CAMERA_HEIGHT - RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); lowerRightCurve.setRotation(270); this.mScene.attachChild(lowerRightCurve); /* Lower Left */ final Sprite lowerLeftCurve = new Sprite(0, CAMERA_HEIGHT - RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); this.mScene.attachChild(lowerLeftCurve); } } private void initRacetrackBorders() { final Shape bottomOuter = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape topOuter = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape leftOuter = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape rightOuter = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final Shape bottomInner = new Rectangle(RACETRACK_WIDTH, CAMERA_HEIGHT - 2 - RACETRACK_WIDTH, CAMERA_WIDTH - 2 * RACETRACK_WIDTH, 2); final Shape topInner = new Rectangle(RACETRACK_WIDTH, RACETRACK_WIDTH, CAMERA_WIDTH - 2 * RACETRACK_WIDTH, 2); final Shape leftInner = new Rectangle(RACETRACK_WIDTH, RACETRACK_WIDTH, 2, CAMERA_HEIGHT - 2 * RACETRACK_WIDTH); final Shape rightInner = new Rectangle(CAMERA_WIDTH - 2 - RACETRACK_WIDTH, RACETRACK_WIDTH, 2, CAMERA_HEIGHT - 2 * RACETRACK_WIDTH); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, bottomOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, topOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, bottomInner, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, topInner, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftInner, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightInner, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(bottomOuter); this.mScene.attachChild(topOuter); this.mScene.attachChild(leftOuter); this.mScene.attachChild(rightOuter); this.mScene.attachChild(bottomInner); this.mScene.attachChild(topInner); this.mScene.attachChild(leftInner); this.mScene.attachChild(rightInner); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 16:44:30 - 29.06.2010 */ public class ParticleSystemNexusExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final float RATE_MIN = 8; private static final float RATE_MAX = 12; private static final int PARTICLES_MAX = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* LowerLeft to LowerRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* LowerRight to LowerLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperLeft to UpperRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperRight to UpperLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.SingleSceneSplitScreenEngine; import org.anddev.andengine.engine.camera.BoundCamera; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class SplitScreenExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 400; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private Camera mChaseCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add boxes.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0, CAMERA_WIDTH, 0, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH * 2, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new SingleSceneSplitScreenEngine(engineOptions, this.mChaseCamera); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); final AnimatedSprite face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion).animate(100); final Body body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); if(this.mFaceCount == 0){ this.mChaseCamera.setChaseEntity(face); } this.mFaceCount++; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.ColorKeyBitmapTextureAtlasSourceDecorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.RectangleBitmapTextureAtlasSourceDecoratorShape; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ColorKeyTextureSourceDecoratorExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mChromaticCircleTextureRegion; private TextureRegion mChromaticCircleColorKeyedTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); /* The actual AssetTextureSource. */ BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); final AssetBitmapTextureAtlasSource baseTextureSource = new AssetBitmapTextureAtlasSource(this, "chromatic_circle.png"); this.mChromaticCircleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, baseTextureSource, 0, 0); /* We will remove both the red and the green segment of the chromatic circle, * by nesting two ColorKeyTextureSourceDecorators around the actual baseTextureSource. */ final int colorKeyRed = Color.rgb(255, 0, 51); // Red segment final int colorKeyGreen = Color.rgb(0, 179, 0); // Green segment final ColorKeyBitmapTextureAtlasSourceDecorator colorKeyBitmapTextureAtlasSource = new ColorKeyBitmapTextureAtlasSourceDecorator(new ColorKeyBitmapTextureAtlasSourceDecorator(baseTextureSource, RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyRed), RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyGreen); this.mChromaticCircleColorKeyedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, colorKeyBitmapTextureAtlasSource, 128, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final int centerX = (CAMERA_WIDTH - this.mChromaticCircleTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mChromaticCircleTextureRegion.getHeight()) / 2; final Sprite chromaticCircle = new Sprite(centerX - 80, centerY, this.mChromaticCircleTextureRegion); final Sprite chromaticCircleColorKeyed = new Sprite(centerX + 80, centerY, this.mChromaticCircleColorKeyedTextureRegion); scene.attachChild(chromaticCircle); scene.attachChild(chromaticCircleColorKeyed); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.svg.adt.ISVGColorMapper; import org.anddev.andengine.extension.svg.adt.SVGDirectColorMapper; import org.anddev.andengine.extension.svg.opengl.texture.atlas.bitmap.SVGBitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureBuilder; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:58:12 - 21.05.2011 */ public class SVGTextureRegionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SIZE = 128; private static final int COUNT = 12; private static final int COLUMNS = 4; private static final int ROWS = (int)Math.ceil((float)COUNT / COLUMNS); // =========================================================== // Fields // =========================================================== private Camera mCamera; private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas; private BaseTextureRegion[] mSVGTestTextureRegions; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA); SVGBitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSVGTestTextureRegions = new BaseTextureRegion[COUNT]; int i = 0; this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 16, 16); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 32, 32); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 64, 64); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 128, 128); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 16, 16); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 64, 64); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 128, 128, new ISVGColorMapper() { @Override public Integer mapColor(final Integer pColor) { if(pColor == null) { return null; } else { /* Swap blue and green channel. */ return Color.argb(0, Color.red(pColor), Color.blue(pColor), Color.green(pColor)); } } }); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 256, 256, new ISVGColorMapper() { @Override public Integer mapColor(final Integer pColor) { if(pColor == null) { return null; } else { /* Swap red and green channel. */ return Color.argb(0, Color.green(pColor), Color.red(pColor), Color.blue(pColor)); } } }); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid.svg", 64, 64, 2, 2); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid.svg", 256, 256, 2, 2); final SVGDirectColorMapper angryPacDroidSVGColorMapper = new SVGDirectColorMapper(); angryPacDroidSVGColorMapper.addColorMapping(0xA7CA4A, 0xEA872A); angryPacDroidSVGColorMapper.addColorMapping(0xC1DA7F, 0xFAA15F); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid.svg", 256, 256, angryPacDroidSVGColorMapper, 2, 2); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid_apples.svg", 256, 256, 2, 2); try { this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1)); } catch (final TextureAtlasSourcePackingException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.5f, 0.5f, 0.5f)); for(int i = 0; i < COUNT; i++) { final int row = i / COLUMNS; final int column = i % COLUMNS; final float centerX = this.mCamera.getWidth() / (COLUMNS + 1) * (column + 1); final float centerY = this.mCamera.getHeight() / (ROWS + 1) * (row + 1); final float x = centerX - SIZE * 0.5f; final float y = centerY - SIZE * 0.5f; final BaseTextureRegion baseTextureRegion = this.mSVGTestTextureRegions[i]; if(baseTextureRegion instanceof TextureRegion) { final TextureRegion textureRegion = (TextureRegion)baseTextureRegion; scene.attachChild(new Sprite(x, y, SIZE, SIZE, textureRegion)); } else if(baseTextureRegion instanceof TiledTextureRegion) { final TiledTextureRegion tiledTextureRegion = (TiledTextureRegion)baseTextureRegion; final AnimatedSprite animatedSprite = new AnimatedSprite(x, y, SIZE, SIZE, tiledTextureRegion); animatedSprite.animate(500); scene.attachChild(animatedSprite); } } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class DigitalOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final int DIALOG_ALLOWDIAGONAL_ID = 0; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private DigitalOnScreenControl mDigitalOnScreenControl; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } }); this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f); this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128); this.mDigitalOnScreenControl.getControlBase().setScale(1.25f); this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f); this.mDigitalOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(this.mDigitalOnScreenControl); return scene; } @Override public void onLoadComplete() { this.showDialog(DIALOG_ALLOWDIAGONAL_ID); } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_ALLOWDIAGONAL_ID: return new AlertDialog.Builder(this) .setTitle("Setup...") .setMessage("Do you wish to allow diagonal directions on the OnScreenControl?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { DigitalOnScreenControlExample.this.mDigitalOnScreenControl.setAllowDiagonal(true); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { DigitalOnScreenControlExample.this.mDigitalOnScreenControl.setAllowDiagonal(false); } }) .create(); } return super.onCreateDialog(pID); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.pool.RunnablePoolItem; import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:56:22 - 15.06.2011 */ public class RunnablePoolUpdateHandlerExample extends BaseExample implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FACE_COUNT = 2; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mTargetFaceIndex = 0; private final Sprite[] mFaces = new Sprite[FACE_COUNT]; private final RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem> mFaceRotateRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem>() { @Override protected FaceRotateRunnablePoolItem onAllocatePoolItem() { return new FaceRotateRunnablePoolItem(); } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to rotate the sprites using RunnablePoolItems.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.registerUpdateHandler(this.mFaceRotateRunnablePoolUpdateHandler); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFaces[0] = new Sprite(centerX - 50, centerY, this.mFaceTextureRegion); this.mFaces[1] = new Sprite(centerX + 50, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFaces[0]); scene.attachChild(this.mFaces[1]); scene.setOnSceneTouchListener(this); return scene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { this.mTargetFaceIndex = (this.mTargetFaceIndex + 1) % FACE_COUNT; final FaceRotateRunnablePoolItem faceRotateRunnablePoolItem = this.mFaceRotateRunnablePoolUpdateHandler.obtainPoolItem(); faceRotateRunnablePoolItem.setTargetFace(this.mFaces[this.mTargetFaceIndex]); this.mFaceRotateRunnablePoolUpdateHandler.postPoolItem(faceRotateRunnablePoolItem); } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public class FaceRotateRunnablePoolItem extends RunnablePoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Sprite mTargetFace; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public void setTargetFace(final Sprite pTargetFace) { this.mTargetFace = pTargetFace; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void run() { this.mTargetFace.setRotation(this.mTargetFace.getRotation() + 45); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.util.HorizontalAlign; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class TextExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.BLACK); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Text textCenter = new Text(100, 60, this.mFont, "Hello AndEngine!\nYou can even have multilined text!", HorizontalAlign.CENTER); final Text textLeft = new Text(100, 200, this.mFont, "Also left aligned!\nLorem ipsum dolor sit amat...", HorizontalAlign.LEFT); final Text textRight = new Text(100, 340, this.mFont, "And right aligned!\nLorem ipsum dolor sit amat...", HorizontalAlign.RIGHT); scene.attachChild(textCenter); scene.attachChild(textLeft); scene.attachChild(textRight); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:13:46 - 15.06.2010 */ public class TouchDragExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch & Drag the face!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2); return true; } }; face.setScale(4); scene.attachChild(face); scene.registerTouchArea(face); scene.setTouchAreaBindingEnabled(true); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsRemoveExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects. Touch an object to remove it.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mBoxFaceTextureRegion.setTextureRegionBufferManaged(false); this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mCircleFaceTextureRegion.setTextureRegionBufferManaged(false); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); return this.mScene; } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { this.removeFace((AnimatedSprite)pTouchArea); return true; } return false; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } face.animate(200, true); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } private void removeFace(final AnimatedSprite face) { final PhysicsConnector facePhysicsConnector = this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(face); this.mPhysicsWorld.unregisterPhysicsConnector(facePhysicsConnector); this.mPhysicsWorld.destroyBody(facePhysicsConnector.getBody()); this.mScene.unregisterTouchArea(face); this.mScene.detachChild(face); System.gc(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.spritesheets.TexturePackerExampleSpritesheet; import org.anddev.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePack; import org.anddev.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePackLoader; import org.anddev.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePackTextureRegionLibrary; import org.anddev.andengine.extension.texturepacker.opengl.texture.util.texturepacker.exception.TexturePackParseException; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; /** * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 9:55:51 - 02.08.2011 */ public class TexturePackerExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private ITexture mSpritesheetTexture; private TexturePackTextureRegionLibrary mSpritesheetTexturePackTextureRegionLibrary; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { try { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); final TexturePack spritesheetTexturePack = new TexturePackLoader(this, "spritesheets/").loadFromAsset(this, "texturepackerexample.xml"); this.mSpritesheetTexture = spritesheetTexturePack.getTexture(); this.mSpritesheetTexturePackTextureRegionLibrary = spritesheetTexturePack.getTexturePackTextureRegionLibrary(); this.mEngine.getTextureManager().loadTexture(this.mSpritesheetTexture); } catch (final TexturePackParseException e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); TextureRegion faceTextureRegion = this.mSpritesheetTexturePackTextureRegionLibrary.get(TexturePackerExampleSpritesheet.FACE_BOX_ID); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - faceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - faceTextureRegion.getHeight()) / 2; /* Create the face and add it to the scene. */ final Sprite face = new Sprite(centerX, centerY, faceTextureRegion); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.util.concurrent.Callable; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.FileUtils; import org.helllabs.android.xmp.ModPlayer; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:51:47 - 13.06.2010 */ public class ModPlayerExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final String SAMPLE_MOD_DIRECTORY = "mfx/"; private static final String SAMPLE_MOD_FILENAME = "lepeltheme.mod"; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mILove8BitTextureRegion; private final ModPlayer mModPlayer = ModPlayer.getInstance(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the image to toggle the playback of this awesome 8-bit style .MOD music.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mILove8BitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "i_love_8_bit.png", 0, 0); if(FileUtils.isFileExistingOnExternalStorage(this, SAMPLE_MOD_DIRECTORY + SAMPLE_MOD_FILENAME)) { this.startPlayingMod(); } else { this.doAsync(R.string.dialog_modplayerexample_loading_to_external_title, R.string.dialog_modplayerexample_loading_to_external_message, new Callable<Void>() { @Override public Void call() throws Exception { FileUtils.ensureDirectoriesExistOnExternalStorage(ModPlayerExample.this, SAMPLE_MOD_DIRECTORY); FileUtils.copyToExternalStorage(ModPlayerExample.this, SAMPLE_MOD_DIRECTORY + SAMPLE_MOD_FILENAME, SAMPLE_MOD_DIRECTORY + SAMPLE_MOD_FILENAME); return null; } }, new Callback<Void>() { @Override public void onCallback(final Void pCallbackValue) { ModPlayerExample.this.startPlayingMod(); } }); } this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int x = (CAMERA_WIDTH - this.mILove8BitTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mILove8BitTextureRegion.getHeight()) / 2; final Sprite iLove8Bit = new Sprite(x, y, this.mILove8BitTextureRegion); scene.attachChild(iLove8Bit); scene.registerTouchArea(iLove8Bit); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { ModPlayerExample.this.mModPlayer.pause(); } return true; } }); return scene; } @Override public void onLoadComplete() { } @Override protected void onDestroy() { super.onDestroy(); ModPlayerExample.this.mModPlayer.stop(); } // =========================================================== // Methods // =========================================================== private void startPlayingMod() { this.mModPlayer.play(FileUtils.getAbsolutePathOnExternalStorage(this, SAMPLE_MOD_DIRECTORY + SAMPLE_MOD_FILENAME)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.text.TickerText; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.util.HorizontalAlign; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class TickerTextExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.BLACK); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Text text = new TickerText(30, 60, this.mFont, "There are also ticker texts!\n\nYou'll see the answer to life & universe in...\n\n5 4 3 2 1...\n\n42\n\nIndeed very funny!", HorizontalAlign.CENTER, 10); text.registerEntityModifier( new SequenceEntityModifier( new ParallelEntityModifier( new AlphaModifier(10, 0.0f, 1.0f), new ScaleModifier(10, 0.5f, 1.0f) ), new RotationModifier(5, 0, 360) ) ); text.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); scene.attachChild(text); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class TextureOptionsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private BitmapTextureAtlas mBitmapTextureAtlasBilinear; private BitmapTextureAtlas mBitmapTextureAtlasRepeating; private TextureRegion mFaceTextureRegion; private TextureRegion mFaceTextureRegionBilinear; private TextureRegion mFaceTextureRegionRepeating; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.DEFAULT); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mBitmapTextureAtlasBilinear = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegionBilinear = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasBilinear, this, "face_box.png", 0, 0); this.mBitmapTextureAtlasRepeating = new BitmapTextureAtlas(32, 32, TextureOptions.REPEATING_NEAREST_PREMULTIPLYALPHA); this.mFaceTextureRegionRepeating = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasRepeating, this, "face_box.png", 0, 0); /* The following statement causes the BitmapTextureAtlas to be printed horizontally 10x on any Sprite that uses it. * So we will later increase the width of such a sprite by the same factor to avoid distortion. */ this.mFaceTextureRegionRepeating.setWidth(10 * this.mFaceTextureRegionRepeating.getWidth()); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mBitmapTextureAtlasBilinear, this.mBitmapTextureAtlasRepeating); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX - 160, centerY - 40, this.mFaceTextureRegion); face.setScale(4); final Sprite faceBilinear = new Sprite(centerX + 160, centerY - 40, this.mFaceTextureRegionBilinear); faceBilinear.setScale(4); /* Make sure sprite has the same size as mTextureRegionRepeating. * Giving the sprite twice the height shows you'd also have to change the height of the TextureRegion! */ final Sprite faceRepeating = new Sprite(centerX - 160, centerY + 100, this.mFaceTextureRegionRepeating.getWidth(), this.mFaceTextureRegionRepeating.getHeight() * 2, this.mFaceTextureRegionRepeating); scene.attachChild(face); scene.attachChild(faceBilinear); scene.attachChild(faceRepeating); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 12:14:29 - 30.06.2010 */ public class LoadTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private Scene mScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to load a completely new BitmapTextureAtlas in a random location with every touch!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* Nothing done here. */ } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.mScene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { LoadTextureExample.this.loadNewTexture(); } return true; } }); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void loadNewTexture() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); final TextureRegion faceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); final float x = (CAMERA_WIDTH - faceTextureRegion.getWidth()) * MathUtils.RANDOM.nextFloat(); final float y = (CAMERA_HEIGHT - faceTextureRegion.getHeight()) * MathUtils.RANDOM.nextFloat(); final Sprite clickToUnload = new Sprite(x, y, faceTextureRegion); this.mScene.attachChild(clickToUnload); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.BoundCamera; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer; import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader; import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader.ITMXTilePropertiesListener; import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties; import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile; import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty; import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap; import org.anddev.andengine.entity.layer.tiled.tmx.util.exception.TMXLoadException; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.constants.Constants; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:58:48 - 19.07.2010 */ public class TMXTiledMapExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private BoundCamera mBoundChaseCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; private TMXTiledMap mTMXTiledMap; protected int mCactusCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The tile the player is walking on will be highlighted.", Toast.LENGTH_LONG).show(); this.mBoundChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mBoundChaseCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); // 72x128 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); try { final TMXLoader tmxLoader = new TMXLoader(this, this.mEngine.getTextureManager(), TextureOptions.BILINEAR_PREMULTIPLYALPHA, new ITMXTilePropertiesListener() { @Override public void onTMXTileWithPropertiesCreated(final TMXTiledMap pTMXTiledMap, final TMXLayer pTMXLayer, final TMXTile pTMXTile, final TMXProperties<TMXTileProperty> pTMXTileProperties) { /* We are going to count the tiles that have the property "cactus=true" set. */ if(pTMXTileProperties.containsTMXProperty("cactus", "true")) { TMXTiledMapExample.this.mCactusCount++; } } }); this.mTMXTiledMap = tmxLoader.loadFromAsset(this, "tmx/desert.tmx"); Toast.makeText(this, "Cactus count in this TMXTiledMap: " + this.mCactusCount, Toast.LENGTH_LONG).show(); } catch (final TMXLoadException tmxle) { Debug.e(tmxle); } final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0); scene.attachChild(tmxLayer); /* Make the camera not exceed the bounds of the TMXEntity. */ this.mBoundChaseCamera.setBounds(0, tmxLayer.getWidth(), 0, tmxLayer.getHeight()); this.mBoundChaseCamera.setBoundsEnabled(true); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight()) / 2; /* Create the sprite and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(centerX, centerY, this.mPlayerTextureRegion); this.mBoundChaseCamera.setChaseEntity(player); final Path path = new Path(5).to(0, 160).to(0, 500).to(600, 500).to(600, 160).to(0, 160); player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { } }))); /* Now we are going to create a rectangle that will always highlight the tile below the feet of the pEntity. */ final Rectangle currentTileRectangle = new Rectangle(0, 0, this.mTMXTiledMap.getTileWidth(), this.mTMXTiledMap.getTileHeight()); currentTileRectangle.setColor(1, 0, 0, 0.25f); scene.attachChild(currentTileRectangle); scene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { /* Get the scene-coordinates of the players feet. */ final float[] playerFootCordinates = player.convertLocalToSceneCoordinates(12, 31); /* Get the tile the feet of the player are currently waking on. */ final TMXTile tmxTile = tmxLayer.getTMXTileAt(playerFootCordinates[Constants.VERTEX_INDEX_X], playerFootCordinates[Constants.VERTEX_INDEX_Y]); if(tmxTile != null) { // tmxTile.setTextureRegion(null); <-- Rubber-style removing of tiles =D currentTileRectangle.setPosition(tmxTile.getTileX(), tmxTile.getTileY()); } } }); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:46 - 18.06.2010 */ public enum Value { // =========================================================== // Elements // =========================================================== ACE, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:13 - 18.06.2010 */ public enum Card { // =========================================================== // Elements // =========================================================== CLUB_ACE(Color.CLUB, Value.ACE), CLUB_ONE(Color.CLUB, Value.ONE), CLUB_TWO(Color.CLUB, Value.TWO), CLUB_THREE(Color.CLUB, Value.THREE), CLUB_FOUR(Color.CLUB, Value.FOUR), CLUB_FIVE(Color.CLUB, Value.FIVE), CLUB_SIX(Color.CLUB, Value.SIX), CLUB_SEVEN(Color.CLUB, Value.SEVEN), CLUB_EIGHT(Color.CLUB, Value.EIGHT), CLUB_NINE(Color.CLUB, Value.NINE), CLUB_TEN(Color.CLUB, Value.TEN), CLUB_JACK(Color.CLUB, Value.JACK), CLUB_QUEEN(Color.CLUB, Value.QUEEN), CLUB_KING(Color.CLUB, Value.KING), DIAMOND_ACE(Color.DIAMOND, Value.ACE), DIAMOND_ONE(Color.DIAMOND, Value.ONE), DIAMOND_TWO(Color.DIAMOND, Value.TWO), DIAMOND_THREE(Color.DIAMOND, Value.THREE), DIAMOND_FOUR(Color.DIAMOND, Value.FOUR), DIAMOND_FIVE(Color.DIAMOND, Value.FIVE), DIAMOND_SIX(Color.DIAMOND, Value.SIX), DIAMOND_SEVEN(Color.DIAMOND, Value.SEVEN), DIAMOND_EIGHT(Color.DIAMOND, Value.EIGHT), DIAMOND_NINE(Color.DIAMOND, Value.NINE), DIAMOND_TEN(Color.DIAMOND, Value.TEN), DIAMOND_JACK(Color.DIAMOND, Value.JACK), DIAMOND_QUEEN(Color.DIAMOND, Value.QUEEN), DIAMOND_KING(Color.DIAMOND, Value.KING), HEART_ACE(Color.HEART, Value.ACE), HEART_ONE(Color.HEART, Value.ONE), HEART_TWO(Color.HEART, Value.TWO), HEART_THREE(Color.HEART, Value.THREE), HEART_FOUR(Color.HEART, Value.FOUR), HEART_FIVE(Color.HEART, Value.FIVE), HEART_SIX(Color.HEART, Value.SIX), HEART_SEVEN(Color.HEART, Value.SEVEN), HEART_EIGHT(Color.HEART, Value.EIGHT), HEART_NINE(Color.HEART, Value.NINE), HEART_TEN(Color.HEART, Value.TEN), HEART_JACK(Color.HEART, Value.JACK), HEART_QUEEN(Color.HEART, Value.QUEEN), HEART_KING(Color.HEART, Value.KING), SPADE_ACE(Color.SPADE, Value.ACE), SPADE_ONE(Color.SPADE, Value.ONE), SPADE_TWO(Color.SPADE, Value.TWO), SPADE_THREE(Color.SPADE, Value.THREE), SPADE_FOUR(Color.SPADE, Value.FOUR), SPADE_FIVE(Color.SPADE, Value.FIVE), SPADE_SIX(Color.SPADE, Value.SIX), SPADE_SEVEN(Color.SPADE, Value.SEVEN), SPADE_EIGHT(Color.SPADE, Value.EIGHT), SPADE_NINE(Color.SPADE, Value.NINE), SPADE_TEN(Color.SPADE, Value.TEN), SPADE_JACK(Color.SPADE, Value.JACK), SPADE_QUEEN(Color.SPADE, Value.QUEEN), SPADE_KING(Color.SPADE, Value.KING); // =========================================================== // Constants // =========================================================== public static final int CARD_WIDTH = 71; public static final int CARD_HEIGHT = 96; // =========================================================== // Fields // =========================================================== public final Color mColor; public final Value mValue; // =========================================================== // Constructors // =========================================================== private Card(final Color pColor, final Value pValue) { this.mColor = pColor; this.mValue = pValue; } // =========================================================== // Getter & Setter // =========================================================== public int getTexturePositionX() { return this.mValue.ordinal() * CARD_WIDTH; } public int getTexturePositionY() { return this.mColor.ordinal() * CARD_HEIGHT; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:33 - 18.06.2010 */ public enum Color { // =========================================================== // Elements // =========================================================== CLUB, // Kreuz DIAMOND, HEART, SPADE; // PIK // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:37 - 21.05.2011 */ public class ConnectionPingClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private long mTimestamp; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionPingClientMessage() { } // =========================================================== // Getter & Setter // =========================================================== public long getTimestamp() { return this.mTimestamp; } public void setTimestamp(final long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_CONNECTION_PING; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mTimestamp = pDataInputStream.readLong(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeLong(this.mTimestamp); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:00 - 21.05.2011 */ public interface ClientMessageFlags { // =========================================================== // Final Fields // =========================================================== /* Connection Flags. */ public static final short FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE = Short.MIN_VALUE; public static final short FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH = FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE + 1; public static final short FLAG_MESSAGE_CLIENT_CONNECTION_PING = FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH + 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:31 - 21.05.2011 */ public class ConnectionEstablishClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private short mProtocolVersion; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionEstablishClientMessage() { } public ConnectionEstablishClientMessage(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Getter & Setter // =========================================================== public short getProtocolVersion() { return this.mProtocolVersion; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return ClientMessageFlags.FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mProtocolVersion = pDataInputStream.readShort(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeShort(this.mProtocolVersion); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:36 - 21.05.2011 */ public class ConnectionCloseClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionCloseClientMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:18:34 - 21.05.2011 */ public class MessageConstants { // =========================================================== // Constants // =========================================================== public static final short PROTOCOL_VERSION = 1; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java