SlideShare a Scribd company logo
allclasses-
frame.htmlAll ClassesAIBoardPlacementRandomModeRotationS
hapeShapeStreamTetris5044
allclasses-
noframe.htmlAll ClassesAIBoardPlacementRandomModeRotatio
nShapeShapeStreamTetris5044
constant-values.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll ClassesConstant Field Values
Contentsedu.vt.*
edu.vt.*
edu.vt.cs5044.tetris.BoardModifier and TypeConstant
FieldValuepublic static final intHEIGHT24public static final int
HEIGHT_LIMIT20public static final intWIDTH10Skip
navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll Classes
deprecated-list.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll ClassesDeprecated API
ContentsSkip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll Classes
edu/vt/cs5044/tetris/Tetris5044.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu.vt.cs5044.tetris
Class Tetris5044ObjectApplicationTetris5044public class
Tetris5044
extends Application
The main application class; for internal use only.
Version:1.0Nested Class SummaryNested classes/interfaces
inherited from class Application
Application.ParametersField SummaryFields inherited from
class Application
STYLESHEET_CASPIAN,
STYLESHEET_MODENAConstructor Summary
Constructors Constructor and DescriptionTetris5044() Method
Summary
All Methods Static MethodsInstance MethodsConcrete
MethodsModifier and TypeMethod and Descriptionstatic
voidmain(String[] args)
For internal use only.
voidstart(Stage primaryStage)
For internal use only.
Methods inherited from class Application
getHostServices, getParameters, getUserAgentStylesheet, init,
launch, launch, notifyPreloader, setUserAgentStylesheet,
stopMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll,
toString, wait, wait, waitConstructor
DetailTetris5044public Tetris5044()Method
Detailstartpublic void start(Stage primaryStage)
throws Exception
For internal use only.
Specified by:start in class ApplicationParameters:primaryStage
- for internal use only.Throws:Exception - for internal use
only.mainpublic static void main(String[] args)
For internal use only.
Parameters:args - ignored.Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu/vt/cs5044/tetris/RandomMode.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Enum
Constants | Field | MethodDetail: Enum
Constants | Field | Method
edu.vt.cs5044.tetris
Enum
RandomModeObjectEnum<RandomMode>RandomModeAll
Implemented Interfaces:Serializable,
Comparable<RandomMode>public enum RandomMode
extends Enum<RandomMode>
Enumerates the modes of randomness used for generating
shapes for games of tetris.
Enum Constant Summary
Enum Constants Enum Constant and DescriptionNORMAL
Stream of randomness that is not repeatable.
TEST1
Repeatable stream of randomness number 1.
TEST2
Repeatable stream of randomness, number 2.
TEST3
Repeatable stream of randomness, number 3.
TEST4
Repeatable streams of randomness, number 4.
Method Summary
All Methods Static MethodsConcrete MethodsModifier and
TypeMethod and Descriptionstatic
Set<RandomMode>getTestSet()
Fetch the set of all test-related values.
static RandomModevalueOf(String name)
Returns the enum constant of this type with the specified name.
static RandomMode[]values()
Returns an array containing the constants of this enum type, in
the order they are declared.
Methods inherited from class Enum
clone, compareTo, equals, finalize, getDeclaringClass,
hashCode, name, ordinal, toString, valueOfMethods inherited
from class Object
getClass, notify, notifyAll, wait, wait, waitEnum Constant
DetailNORMALpublic static final RandomMode NORMAL
Stream of randomness that is not repeatable.
TEST1public static final RandomMode TEST1
Repeatable stream of randomness number 1.
TEST2public static final RandomMode TEST2
Repeatable stream of randomness, number 2.
TEST3public static final RandomMode TEST3
Repeatable stream of randomness, number 3.
TEST4public static final RandomMode TEST4
Repeatable streams of randomness, number 4.
Method Detailvaluespublic static RandomMode[] values()
Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
for (RandomMode c : RandomMode.values())
System.out.println(c);
Returns:an array containing the constants of this enum type, in
the order they are declaredvalueOfpublic
static RandomMode valueOf(String name)
Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters
are
not permitted.)
Parameters:name - the name of the enum constant to be
returned.Returns:the enum constant with the specified
nameThrows:IllegalArgumentException - if this enum type has
no constant with the specified nameNullPointerException - if
the argument is nullgetTestSetpublic
static Set<RandomMode> getTestSet()
Fetch the set of all test-related values.
This set includes all RandomMode values except NORMAL.
Returns:set of test-related values.Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Enum
Constants | Field | MethodDetail: Enum
Constants | Field | Method
edu/vt/cs5044/tetris/package-frame.htmledu.vt.cs5044.tetris
InterfacesAI
ClassesBoardPlacementShapeStreamTetris5044
EnumsRandomModeRotationShape
edu/vt/cs5044/tetris/Placement.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu.vt.cs5044.tetris
Class PlacementObjectPlacementpublic class Placement
extends Object
Represents a single possible placement of a shape.
The placement is specified by a rotation along with the
horizontal location of the
left-most block of the rotated shape
Constructor Summary
Constructors Constructor and
DescriptionPlacement(Rotation rotation,
int column)
Construct a new object with the specified parameters.
Method Summary
All Methods Instance MethodsConcrete MethodsModifier and
TypeMethod and Descriptionbooleanequals(Object obj)
Test for equality with another Placement.
intgetColumn()
Fetch specified column.
RotationgetRotation()
Fetch specified rotation.
inthashCode()StringtoString()
Generates a simple human-readable representation of this
object.
Methods inherited from class Object
clone, finalize, getClass, notify, notifyAll, wait, wait,
waitConstructor
DetailPlacementpublic Placement(Rotation rotation,
int column)
Construct a new object with the specified parameters.
Parameters:rotation - number of rotations to apply to the
shape.column - left-most block of the rotated shape goes in this
column.Method DetailgetRotationpublic Rotation getRotation()
Fetch specified rotation.
Returns:rotation.getColumnpublic int getColumn()
Fetch specified column.
The left-most column of the board is 0.
The left-most block of the rotated shape goes in the specified
column.
Returns:column.toStringpublic String toString()
Generates a simple human-readable representation of this
object.
Overrides:toString in class ObjectReturns:simple representation
of this object.equalspublic boolean equals(Object obj)
Test for equality with another Placement.
Two placements are equal if and only if they contain the same
column and rotation values.
Overrides:equals in class ObjectParameters:obj - the other
placement.Returns:true if the placements are equivalent; false
otherwise.hashCodepublic int hashCode()Overrides:hashCode in
class ObjectSkip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu/vt/cs5044/tetris/Board.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu.vt.cs5044.tetris
Class BoardObjectBoardpublic class Board
extends Object
Represents a Tetris game board, including all fixed blocks.
This class is effectively immutable, because there are no public
mutators.
Field Summary
Fields Modifier and TypeField and Descriptionstatic
intHEIGHT
Height of all game boards, in blocks.
static intHEIGHT_LIMIT
Height limit of all game boards, in blocks.
static intWIDTH
Width of all game boards, in blocks.
Constructor Summary
Constructors Constructor and DescriptionBoard()
Construct a new empty board with no fixed blocks.
Board(String... initialBlocks)
Construct a new board with the specified initial blocks.
Method Summary
All Methods Instance MethodsConcrete MethodsModifier and
TypeMethod and Descriptionbooleanequals(Object obj)
Test for equality with another Board.
BoardgetResultBoard(Shape shape,
Placement place)
Generate a new board that is the result of placing a shape in this
board.
inthashCode()booleanisBlockAt(int col,
int row)
Check for a fixed block at a specified location.
StringtoString()
Generate a multi-line ASCII art visualization of this board.
Methods inherited from class Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitField
DetailWIDTHpublic static final int WIDTH
Width of all game boards, in blocks.
See Also:Constant Field ValuesHEIGHTpublic static final int
HEIGHT
Height of all game boards, in blocks.
See Also:Constant Field ValuesHEIGHT_LIMITpublic static
final int HEIGHT_LIMIT
Height limit of all game boards, in blocks.
If any block becomes fixed at or above this row index, the
game ends.
See Also:Constant Field ValuesConstructor
DetailBoardpublic Board()
Construct a new empty board with no fixed blocks.
Boardpublic Board(String... initialBlocks)
Construct a new board with the specified initial blocks.
Specify a variable number of String values as arguments.
Each String represents one row of the board.
The last row is placed at the bottom of the board.
No more than HEIGHT_LIMIT rows may be specified.
If fewer rows are specified, the unspecified rows will be empty.
Each row must have exactly WIDTH characters.
The first character represents the left edge of the board.
Each character must be either a space ' ' or a hash '#'.
A hash means a single fixed block exists at that position.
A space means no fixed block exists at that position.
Parameters:initialBlocks - blocks to include in the boardMethod
DetailisBlockAtpublic boolean isBlockAt(int col,
int row)
Check for a fixed block at a specified location.
Parameters:col - column number; left-most column is zerorow -
row number; bottom-most row is zeroReturns:true if a fixed
block is at this location; false
otherwisegetResultBoardpublic Board getResultBoard(Shape sh
ape,
Placement place)
Generate a new board that is the result of placing a shape in this
board.
First a copy of this board is created.
The shape is placed at the top of this copy, rotated according to
the placement,
then moved horizontally such that the left-most block is in the
specified column.
The block is then dropped until it locks into place, then all
completely full rows (if any)
are cleared as in normal play. The result of this activity is
returned.
Note: This method is not a mutator; it does not change this
board object.Parameters:shape - the Shape to place.place - a
Placement containing the rotation and location of the
shape.Returns:a new Board representing the result of the
placement.toStringpublic String toString()
Generate a multi-line ASCII art visualization of this board.
The walls of the board are represented as '*' characters above
the
HEIGHT_LIMIT, and as '|' characters otherwise.
The bottom of the board is represented by a row of '-'
characters.
Fixed blocks are represented by '#' characters.
Overrides:toString in class ObjectReturns:a rudimentary
depiction of the board.equalspublic boolean equals(Object obj)
Test for equality with another Board.
Two boards are equal if and only if they contain the same
arrangement
of fixed blocks.
Overrides:equals in class ObjectParameters:obj - the other
board.Returns:true if the boards are equivalent; false
otherwise.hashCodepublic int hashCode()Overrides:hashCode in
class ObjectSkip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu/vt/cs5044/tetris/AI.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu.vt.cs5044.tetris
Interface AIpublic interface AI
Interface the game engine uses to communicate with AI
implementations.
You must develop an implementation of this interface.
Method Summary
All Methods Instance MethodsAbstract MethodsModifier and
TypeMethod and
DescriptionPlacementfindBestPlacement(Board currentBoard,
Shape shape)
Calculate the best placement available for a shape in a board.
intgetColumnHeightVariability(Board board)
Return the variability of column heights of a board (see
academic note).
intgetMaximumBlockHeight(Board board)
Compute the maximum block height of a board (see academic
note).
intgetTotalBlockCount(Board board)
Compute the total block count of a board (see academic note).
intgetTotalGapCount(Board board)
Compute the total gap count of a board (see academic note).
Method
DetailfindBestPlacementPlacement findBestPlacement(Board cu
rrentBoard,
Shape shape)
Calculate the best placement available for a shape in a board.
All possible columns for all possible rotations of the given
shape should be considered.
For each combination, implementations should call
Board.getResultBoard(Shape, Placement)
to generate the resultant board after a hypothetical placement.
The implementation must calculate a relative cost value for ech
resultant board,
then return the Placement object associated with the lowest
cost (most preferable).
Parameters:currentBoard - the existing board.shape - the shape
to be placed in the board.Returns:the best move as computed by
the
implementation.getMaximumBlockHeightint getMaximumBlock
Height(Board board)
Compute the maximum block height of a board (see academic
note).
Finds the height of the upper-most block within a board.
Note that a block in row r has a height of r+1.
ACADEMIC NOTE: This method would normally be declared
as private.
We're exposing it as public only for testing
purposes.Parameters:board - the Board to evaluate.Returns:the
height of the of block in the largest row
number.getTotalBlockCountint getTotalBlockCount(Board boar
d)
Compute the total block count of a board (see academic note).
Counts the total number of blocks residing within a board.
ACADEMIC NOTE: This method would normally be declared
as private.
We're exposing it as public only for testing
purposes.Parameters:board - the Board to evaluate.Returns:the
total number of
blocks.getTotalGapCountint getTotalGapCount(Board board)
Compute the total gap count of a board (see academic note).
Counts the number of gaps residing within a board.
A gap is a location without a block, where a block exists in any
higher row
of the same column.
ACADEMIC NOTE: This method would normally be declared
as private.
We're exposing it as public only for testing
purposes.Parameters:board - the Board to evaluate.Returns:the
number of
gaps.getColumnHeightVariabilityint getColumnHeightVariabilit
y(Board board)
Return the variability of column heights of a board (see
academic note).
The variability is defined here as the sum of the absolute
values of differences in
heights of adjacent columns, as measure from either edge of the
board to the other.
Note that for a board width w, there are w-1 adjacent column
heights.
ACADEMIC NOTE: This method would normally be declared
as private.
We're exposing it as public only for testing
purposes.Parameters:board - the Board to evaluate.Returns:the
variability of column heights.Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu/vt/cs5044/tetris/package-summary.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev PackageNext Packa
geFramesNo FramesAll ClassesPackage edu.vt.cs5044.tetris
This package holds the internal components necessary for the
game.
See: Description
Interface Summary InterfaceDescriptionAI
Interface the game engine uses to communicate with AI
implementations.
Class Summary ClassDescriptionBoard
Represents a Tetris game board, including all fixed blocks.
Placement
Represents a single possible placement of a shape.
ShapeStream
Used to generate a stream of random shapes for a game of
Tetris.
Tetris5044
The main application class; for internal use only.
Enum Summary EnumDescriptionRandomMode
Enumerates the modes of randomness used for generating
shapes for games of tetris.
Rotation
Enumeration representing each of the four distinct rotations in
Tetris.
Shape
Enumeration representing each of the seven distinct tetromino
shapes.
Package edu.vt.cs5044.tetris Description
This package holds the internal components necessary for the
game.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev PackageNext Packa
geFramesNo FramesAll Classes
edu/vt/cs5044/tetris/ShapeStream.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu.vt.cs5044.tetris
Class ShapeStreamObjectShapeStreampublic class ShapeStream
extends Object
Used to generate a stream of random shapes for a game of
Tetris.
Constructor Summary
Constructors Constructor and
DescriptionShapeStream(RandomMode mode)
Construct a new ShapeStream in the specified RandomMode.
Method Summary
All Methods Instance MethodsConcrete MethodsModifier and
TypeMethod and DescriptionShapenextShape()
Fetch the next random Shape from this stream.
Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll,
toString, wait, wait, waitConstructor
DetailShapeStreampublic ShapeStream(RandomMode mode)
Construct a new ShapeStream in the specified RandomMode.
Parameters:mode - specifies the strategy for generating the
random sequence; must not be null.Method
DetailnextShapepublic Shape nextShape()
Fetch the next random Shape from this stream.
Returns:the next random Shape from this stream.Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
ethodDetail: Field | Constr | Method
edu/vt/cs5044/tetris/Shape.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Enum
Constants | Field | MethodDetail: Enum
Constants | Field | Method
edu.vt.cs5044.tetris
Enum ShapeObjectEnum<Shape>ShapeAll Implemented
Interfaces:Serializable, Comparable<Shape>public enum Shape
extends Enum<Shape>
Enumeration representing each of the seven distinct tetromino
shapes.
Enum Constant Summary
Enum Constants Enum Constant and DescriptionI
The "I" shape.
J
The "J" shape.
L
The "L" shape.
O
The "O" shape.
S
The "S" shape.
T
The "T" shape.
Z
The "Z" shape.
Method Summary
All Methods Static MethodsInstance MethodsConcrete
MethodsModifier and TypeMethod and
DescriptionSet<Rotation>getRotationSet()
Get the set of valid rotations for this shape.
intgetWidth(Rotation r)
Get the width of this shape, in blocks, after applying a specified
rotation.
static ShapevalueOf(String name)
Returns the enum constant of this type with the specified name.
static Shape[]values()
Returns an array containing the constants of this enum type, in
the order they are declared.
Methods inherited from class Enum
clone, compareTo, equals, finalize, getDeclaringClass,
hashCode, name, ordinal, toString, valueOfMethods inherited
from class Object
getClass, notify, notifyAll, wait, wait, waitEnum Constant
DetailIpublic static final Shape I
The "I" shape.
Opublic static final Shape O
The "O" shape.
Tpublic static final Shape T
The "T" shape.
Jpublic static final Shape J
The "J" shape.
Lpublic static final Shape L
The "L" shape.
Spublic static final Shape S
The "S" shape.
Zpublic static final Shape Z
The "Z" shape.
Method Detailvaluespublic static Shape[] values()
Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
for (Shape c : Shape.values())
System.out.println(c);
Returns:an array containing the constants of this enum type, in
the order they are declaredvalueOfpublic
static Shape valueOf(String name)
Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters
are
not permitted.)
Parameters:name - the name of the enum constant to be
returned.Returns:the enum constant with the specified
nameThrows:IllegalArgumentException - if this enum type has
no constant with the specified nameNullPointerException - if
the argument is
nullgetRotationSetpublic Set<Rotation> getRotationSet()
Get the set of valid rotations for this shape.
Returns a set of Rotation values that can be applied to this
shape to result in
distinct orientations.
Returns:the a set of Rotation
values.getWidthpublic int getWidth(Rotation r)
Get the width of this shape, in blocks, after applying a specified
rotation.
The rotation parameter must be contained in the Set returned by
getRotationSet().
Parameters:r - the rotation to apply.Returns:the width of the
rotated shape, in blocks.Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Enum
Constants | Field | MethodDetail: Enum
Constants | Field | Method
edu/vt/cs5044/tetris/Rotation.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Enum
Constants | Field | MethodDetail: Enum
Constants | Field | Method
edu.vt.cs5044.tetris
Enum RotationObjectEnum<Rotation>RotationAll Implemented
Interfaces:Serializable, Comparable<Rotation>public enum
Rotation
extends Enum<Rotation>
Enumeration representing each of the four distinct rotations in
Tetris.
Enum Constant Summary
Enum Constants Enum Constant and DescriptionCCW_180
Rotate 180° counter-clockwise.
CCW_270
Rotate 270° counter-clockwise.
CCW_90
Rotate 90° counter-clockwise.
NONE
No rotation; the default orientation.
Method Summary
All Methods Static MethodsConcrete MethodsModifier and
TypeMethod and Descriptionstatic
RotationvalueOf(String name)
Returns the enum constant of this type with the specified name.
static Rotation[]values()
Returns an array containing the constants of this enum type, in
the order they are declared.
Methods inherited from class Enum
clone, compareTo, equals, finalize, getDeclaringClass,
hashCode, name, ordinal, toString, valueOfMethods inherited
from class Object
getClass, notify, notifyAll, wait, wait, waitEnum Constant
DetailNONEpublic static final Rotation NONE
No rotation; the default orientation.
CCW_90public static final Rotation CCW_90
Rotate 90° counter-clockwise.
CCW_180public static final Rotation CCW_180
Rotate 180° counter-clockwise.
CCW_270public static final Rotation CCW_270
Rotate 270° counter-clockwise.
Method Detailvaluespublic static Rotation[] values()
Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
for (Rotation c : Rotation.values())
System.out.println(c);
Returns:an array containing the constants of this enum type, in
the order they are declaredvalueOfpublic
static Rotation valueOf(String name)
Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters
are
not permitted.)
Parameters:name - the name of the enum constant to be
returned.Returns:the enum constant with the specified
nameThrows:IllegalArgumentException - if this enum type has
no constant with the specified nameNullPointerException - if
the argument is nullSkip navigation
linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
amesNo FramesAll ClassesSummary: Nested | Enum
Constants | Field | MethodDetail: Enum
Constants | Field | Method
help-doc.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll ClassesHow This API Document Is Organized
This API (Application Programming Interface) document has
pages corresponding to the items in the navigation bar,
described as follows.
Package
Each package has a page that contains a list of its classes and
interfaces, with a summary for each. This page can contain six
categories:Interfaces
(italic)ClassesEnumsExceptionsErrorsAnnotation Types
Class/Interface
Each class, interface, nested class and nested interface has its
own separate page. Each of these pages has three sections
consisting of a class/interface description, summary tables, and
detailed member descriptions:Class inheritance diagramDirect
SubclassesAll Known SubinterfacesAll Known Implementing
ClassesClass/interface declarationClass/interface
descriptionNested Class SummaryField SummaryConstructor
SummaryMethod SummaryField DetailConstructor
DetailMethod Detail
Each summary entry contains the first sentence from the
detailed description for that item. The summary entries are
alphabetical, while the detailed descriptions are in the order
they appear in the source code. This preserves the logical
groupings established by the programmer.
Annotation Type
Each annotation type has its own separate page with the
following sections:Annotation Type declarationAnnotation Type
descriptionRequired Element SummaryOptional Element
SummaryElement Detail
Enum
Each enum has its own separate page with the following
sections:Enum declarationEnum descriptionEnum Constant
SummaryEnum Constant Detail
Deprecated API
The Deprecated API page lists all of the API that have been
deprecated. A deprecated API is not recommended for use,
generally due to improvements, and a replacement API is
usually given. Deprecated APIs may be removed in future
implementations.
Index
The Index contains an alphabetic list of all classes, interfaces,
constructors, methods, and fields.
Prev/Next
These links take you to the next or previous class, interface,
package, or related page.
Frames/No Frames
These links show and hide the HTML frames. All pages are
available with or without frames.
All Classes
The All Classes link shows all classes and interfaces except
non-static nested types.
Serialized Form
Each serializable or externalizable class has a description of its
serialization fields and methods. This information is of interest
to re-implementors, not to developers using the API. While
there is no link in the navigation bar, you can get to this
information by going to any serialized class and clicking
"Serialized Form" in the "See also" section of the class
description.
Constant Field Values
The Constant Field Values page lists the static final fields and
their values.
This help file applies to API documentation generated using the
standard doclet.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll Classes
index-all.html
JavaScript is disabled on your browser.
Skip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll ClassesABEFGHIMNPRSTVW
AAI - Interface in edu.vt.cs5044.tetris
Interface the game engine uses to communicate with AI
implementations.
BBoard - Class in edu.vt.cs5044.tetris
Represents a Tetris game board, including all fixed blocks.
Board() - Constructor for class Board
Construct a new empty board with no fixed blocks.
Board(String...) - Constructor for class Board
Construct a new board with the specified initial blocks.
Eedu.vt.cs5044.tetris - package edu.vt.cs5044.tetris
This package holds the internal components necessary for the
game.
equals(Object) - Method in class Board
Test for equality with another Board.
equals(Object) - Method in class Placement
Test for equality with another Placement.
FfindBestPlacement(Board, Shape) - Method in interface AI
Calculate the best placement available for a shape in a board.
GgetColumn() - Method in class Placement
Fetch specified column.
getColumnHeightVariability(Board) - Method in interface AI
Return the variability of column heights of a board (see
academic note).
getMaximumBlockHeight(Board) - Method in interface AI
Compute the maximum block height of a board (see academic
note).
getResultBoard(Shape, Placement) - Method in class Board
Generate a new board that is the result of placing a shape in this
board.
getRotation() - Method in class Placement
Fetch specified rotation.
getRotationSet() - Method in enum Shape
Get the set of valid rotations for this shape.
getTestSet() - Static method in enum RandomMode
Fetch the set of all test-related values.
getTotalBlockCount(Board) - Method in interface AI
Compute the total block count of a board (see academic note).
getTotalGapCount(Board) - Method in interface AI
Compute the total gap count of a board (see academic note).
getWidth(Rotation) - Method in enum Shape
Get the width of this shape, in blocks, after applying a specified
rotation.
HhashCode() - Method in class BoardhashCode() - Method in
class PlacementHEIGHT - Static variable in class Board
Height of all game boards, in blocks.
HEIGHT_LIMIT - Static variable in class Board
Height limit of all game boards, in blocks.
IisBlockAt(int, int) - Method in class Board
Check for a fixed block at a specified location.
Mmain(String[]) - Static method in class Tetris5044
For internal use only.
NnextShape() - Method in class ShapeStream
Fetch the next random Shape from this stream.
PPlacement - Class in edu.vt.cs5044.tetris
Represents a single possible placement of a shape.
Placement(Rotation, int) - Constructor for class Placement
Construct a new object with the specified parameters.
RRandomMode - Enum in edu.vt.cs5044.tetris
Enumerates the modes of randomness used for generating
shapes for games of tetris.
Rotation - Enum in edu.vt.cs5044.tetris
Enumeration representing each of the four distinct rotations in
Tetris.
SShape - Enum in edu.vt.cs5044.tetris
Enumeration representing each of the seven distinct tetromino
shapes.
ShapeStream - Class in edu.vt.cs5044.tetris
Used to generate a stream of random shapes for a game of
Tetris.
ShapeStream(RandomMode) - Constructor for class
ShapeStream
Construct a new ShapeStream in the specified RandomMode.
start(Stage) - Method in class Tetris5044
For internal use only.
TTetris5044 - Class in edu.vt.cs5044.tetris
The main application class; for internal use only.
Tetris5044() - Constructor for class Tetris5044toString() -
Method in class Board
Generate a multi-line ASCII art visualization of this board.
toString() - Method in class Placement
Generates a simple human-readable representation of this
object.
VvalueOf(String) - Static method in enum RandomMode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum Rotation
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum Shape
Returns the enum constant of this type with the specified name.
values() - Static method in enum RandomMode
Returns an array containing the constants of this enum type, in
the order they are declared.
values() - Static method in enum Rotation
Returns an array containing the constants of this enum type, in
the order they are declared.
values() - Static method in enum Shape
Returns an array containing the constants of this enum type, in
the order they are declared.
WWIDTH - Static variable in class Board
Width of all game boards, in blocks.
ABEFGHIMNPRSTVWSkip navigation
linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
mesAll Classes
index.html
package-list
edu.vt.cs5044.tetris
script.js
function show(type)
{
count = 0;
for (var key in methods) {
var row = document.getElementById(key);
if ((methods[key] & type) != 0) {
row.style.display = '';
row.className = (count++ % 2) ? rowColor : altColor;
}
else
row.style.display = 'none';
}
updateTabs(type);
}
function updateTabs(type)
{
for (var value in tabs) {
var sNode = document.getElementById(tabs[value][0]);
var spanNode = sNode.firstChild;
if (value == type) {
sNode.className = activeTableTab;
spanNode.innerHTML = tabs[value][1];
}
else {
sNode.className = tableTab;
spanNode.innerHTML = "<a href="javascript:show("+
value + ");">" + tabs[value][1] + "</a>";
}
}
}
stylesheet.css
/* Javadoc style sheet */
/*
Overall document style
*/
@import url('resources/fonts/dejavu.css');
body {
background-color:#ffffff;
color:#353833;
font-family:'DejaVu Sans', Arial, Helvetica, sans-serif;
font-size:14px;
margin:0;
}
a:link, a:visited {
text-decoration:none;
color:#4A6782;
}
a:hover, a:focus {
text-decoration:none;
color:#bb7a2a;
}
a:active {
text-decoration:none;
color:#4A6782;
}
a[name] {
color:#353833;
}
a[name]:hover {
text-decoration:none;
color:#353833;
}
pre {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
}
h1 {
font-size:20px;
}
h2 {
font-size:18px;
}
h3 {
font-size:16px;
font-style:italic;
}
h4 {
font-size:13px;
}
h5 {
font-size:12px;
}
h6 {
font-size:11px;
}
ul {
list-style-type:disc;
}
code, tt {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
padding-top:4px;
margin-top:8px;
line-height:1.4em;
}
dt code {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
padding-top:4px;
}
table tr td dt code {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
vertical-align:top;
padding-top:4px;
}
sup {
font-size:8px;
}
/*
Document title and Copyright styles
*/
.clear {
clear:both;
height:0px;
overflow:hidden;
}
.aboutLanguage {
float:right;
padding:0px 21px;
font-size:11px;
z-index:200;
margin-top:-9px;
}
.legalCopy {
margin-left:.5em;
}
.bar a, .bar a:link, .bar a:visited, .bar a:active {
color:#FFFFFF;
text-decoration:none;
}
.bar a:hover, .bar a:focus {
color:#bb7a2a;
}
.tab {
background-color:#0066FF;
color:#ffffff;
padding:8px;
width:5em;
font-weight:bold;
}
/*
Navigation bar styles
*/
.bar {
background-color:#4D7A97;
color:#FFFFFF;
padding:.8em .5em .4em .8em;
height:auto;/*height:1.8em;*/
font-size:11px;
margin:0;
}
.topNav {
background-color:#4D7A97;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
font-size:12px;
}
.bottomNav {
margin-top:10px;
background-color:#4D7A97;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
font-size:12px;
}
.subNav {
background-color:#dee3e9;
float:left;
width:100%;
overflow:hidden;
font-size:12px;
}
.subNav div {
clear:left;
float:left;
padding:0 0 5px 6px;
text-transform:uppercase;
}
ul.navList, ul.subNavList {
float:left;
margin:0 25px 0 0;
padding:0;
}
ul.navList li{
list-style:none;
float:left;
padding: 5px 6px;
text-transform:uppercase;
}
ul.subNavList li{
list-style:none;
float:left;
}
.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav
a:link, .bottomNav a:active, .bottomNav a:visited {
color:#FFFFFF;
text-decoration:none;
text-transform:uppercase;
}
.topNav a:hover, .bottomNav a:hover {
text-decoration:none;
color:#bb7a2a;
text-transform:uppercase;
}
.navBarCell1Rev {
background-color:#F8981D;
color:#253441;
margin: auto 5px;
}
.skipNav {
position:absolute;
top:auto;
left:-9999px;
overflow:hidden;
}
/*
Page header and footer styles
*/
.header, .footer {
clear:both;
margin:0 20px;
padding:5px 0 0 0;
}
.indexHeader {
margin:10px;
position:relative;
}
.indexHeader span{
margin-right:15px;
}
.indexHeader h1 {
font-size:13px;
}
.title {
color:#2c4557;
margin:10px 0;
}
.subTitle {
margin:5px 0 0 0;
}
.header ul {
margin:0 0 15px 0;
padding:0;
}
.footer ul {
margin:20px 0 5px 0;
}
.header ul li, .footer ul li {
list-style:none;
font-size:13px;
}
/*
Heading styles
*/
div.details ul.blockList ul.blockList ul.blockList li.blockList
h4, div.details ul.blockList ul.blockList ul.blockListLast
li.blockList h4 {
background-color:#dee3e9;
border:1px solid #d0d9e0;
margin:0 0 6px -8px;
padding:7px 5px;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
background-color:#dee3e9;
border:1px solid #d0d9e0;
margin:0 0 6px -8px;
padding:7px 5px;
}
ul.blockList ul.blockList li.blockList h3 {
padding:0;
margin:15px 0;
}
ul.blockList li.blockList h2 {
padding:0px 0 20px 0;
}
/*
Page layout container styles
*/
.contentContainer, .sourceContainer, .classUseContainer,
.serializedFormContainer, .constantValuesContainer {
clear:both;
padding:10px 20px;
position:relative;
}
.indexContainer {
margin:10px;
position:relative;
font-size:12px;
}
.indexContainer h2 {
font-size:13px;
padding:0 0 3px 0;
}
.indexContainer ul {
margin:0;
padding:0;
}
.indexContainer ul li {
list-style:none;
padding-top:2px;
}
.contentContainer .description dl dt, .contentContainer .details
dl dt, .serializedFormContainer dl dt {
font-size:12px;
font-weight:bold;
margin:10px 0 0 0;
color:#4E4E4E;
}
.contentContainer .description dl dd, .contentContainer .details
dl dd, .serializedFormContainer dl dd {
margin:5px 0 10px 0px;
font-size:14px;
font-family:'DejaVu Sans Mono',monospace;
}
.serializedFormContainer dl.nameValue dt {
margin-left:1px;
font-size:1.1em;
display:inline;
font-weight:bold;
}
.serializedFormContainer dl.nameValue dd {
margin:0 0 0 1px;
font-size:1.1em;
display:inline;
}
/*
List styles
*/
ul.horizontal li {
display:inline;
font-size:0.9em;
}
ul.inheritance {
margin:0;
padding:0;
}
ul.inheritance li {
display:inline;
list-style:none;
}
ul.inheritance li ul.inheritance {
margin-left:15px;
padding-left:15px;
padding-top:1px;
}
ul.blockList, ul.blockListLast {
margin:10px 0 10px 0;
padding:0;
}
ul.blockList li.blockList, ul.blockListLast li.blockList {
list-style:none;
margin-bottom:15px;
line-height:1.4;
}
ul.blockList ul.blockList li.blockList, ul.blockList
ul.blockListLast li.blockList {
padding:0px 20px 5px 10px;
border:1px solid #ededed;
background-color:#f8f8f8;
}
ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList
ul.blockList ul.blockListLast li.blockList {
padding:0 0 5px 8px;
background-color:#ffffff;
border:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockList {
margin-left:0;
padding-left:0;
padding-bottom:15px;
border:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList
li.blockListLast {
list-style:none;
border-bottom:none;
padding-bottom:0;
}
table tr td dl, table tr td dl dt, table tr td dl dd {
margin-top:0;
margin-bottom:1px;
}
/*
Table styles
*/
.overviewSummary, .memberSummary, .typeSummary,
.useSummary, .constantsSummary, .deprecatedSummary {
width:100%;
border-left:1px solid #EEE;
border-right:1px solid #EEE;
border-bottom:1px solid #EEE;
}
.overviewSummary, .memberSummary {
padding:0px;
}
.overviewSummary caption, .memberSummary caption,
.typeSummary caption,
.useSummary caption, .constantsSummary caption,
.deprecatedSummary caption {
position:relative;
text-align:left;
background-repeat:no-repeat;
color:#253441;
font-weight:bold;
clear:none;
overflow:hidden;
padding:0px;
padding-top:10px;
padding-left:1px;
margin:0px;
white-space:pre;
}
.overviewSummary caption a:link, .memberSummary caption
a:link, .typeSummary caption a:link,
.useSummary caption a:link, .constantsSummary caption a:link,
.deprecatedSummary caption a:link,
.overviewSummary caption a:hover, .memberSummary caption
a:hover, .typeSummary caption a:hover,
.useSummary caption a:hover, .constantsSummary caption
a:hover, .deprecatedSummary caption a:hover,
.overviewSummary caption a:active, .memberSummary caption
a:active, .typeSummary caption a:active,
.useSummary caption a:active, .constantsSummary caption
a:active, .deprecatedSummary caption a:active,
.overviewSummary caption a:visited, .memberSummary caption
a:visited, .typeSummary caption a:visited,
.useSummary caption a:visited, .constantsSummary caption
a:visited, .deprecatedSummary caption a:visited {
color:#FFFFFF;
}
.overviewSummary caption span, .memberSummary caption
span, .typeSummary caption span,
.useSummary caption span, .constantsSummary caption span,
.deprecatedSummary caption span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
padding-bottom:7px;
display:inline-block;
float:left;
background-color:#F8981D;
border: none;
height:16px;
}
.memberSummary caption span.activeTableTab span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
margin-right:3px;
display:inline-block;
float:left;
background-color:#F8981D;
height:16px;
}
.memberSummary caption span.tableTab span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
margin-right:3px;
display:inline-block;
float:left;
background-color:#4D7A97;
height:16px;
}
.memberSummary caption span.tableTab, .memberSummary
caption span.activeTableTab {
padding-top:0px;
padding-left:0px;
padding-right:0px;
background-image:none;
float:none;
display:inline;
}
.overviewSummary .tabEnd, .memberSummary .tabEnd,
.typeSummary .tabEnd,
.useSummary .tabEnd, .constantsSummary .tabEnd,
.deprecatedSummary .tabEnd {
display:none;
width:5px;
position:relative;
float:left;
background-color:#F8981D;
}
.memberSummary .activeTableTab .tabEnd {
display:none;
width:5px;
margin-right:3px;
position:relative;
float:left;
background-color:#F8981D;
}
.memberSummary .tableTab .tabEnd {
display:none;
width:5px;
margin-right:3px;
position:relative;
background-color:#4D7A97;
float:left;
}
.overviewSummary td, .memberSummary td, .typeSummary td,
.useSummary td, .constantsSummary td, .deprecatedSummary td
{
text-align:left;
padding:0px 0px 12px 10px;
width:100%;
}
th.colOne, th.colFirst, th.colLast, .useSummary th,
.constantsSummary th,
td.colOne, td.colFirst, td.colLast, .useSummary td,
.constantsSummary td{
vertical-align:top;
padding-right:0px;
padding-top:8px;
padding-bottom:3px;
}
th.colFirst, th.colLast, th.colOne, .constantsSummary th {
background:#dee3e9;
text-align:left;
padding:8px 3px 3px 7px;
}
td.colFirst, th.colFirst {
white-space:nowrap;
font-size:13px;
}
td.colLast, th.colLast {
font-size:13px;
}
td.colOne, th.colOne {
font-size:13px;
}
.overviewSummary td.colFirst, .overviewSummary th.colFirst,
.overviewSummary td.colOne, .overviewSummary th.colOne,
.memberSummary td.colFirst, .memberSummary th.colFirst,
.memberSummary td.colOne, .memberSummary th.colOne,
.typeSummary td.colFirst{
width:25%;
vertical-align:top;
}
td.colOne a:link, td.colOne a:active, td.colOne a:visited,
td.colOne a:hover, td.colFirst a:link, td.colFirst a:active,
td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link,
td.colLast a:active, td.colLast a:visited, td.colLast a:hover,
.constantValuesContainer td a:link, .constantValuesContainer td
a:active, .constantValuesContainer td a:visited,
.constantValuesContainer td a:hover {
font-weight:bold;
}
.tableSubHeadingColor {
background-color:#EEEEFF;
}
.altColor {
background-color:#FFFFFF;
}
.rowColor {
background-color:#EEEEEF;
}
/*
Content styles
*/
.description pre {
margin-top:0;
}
.deprecatedContent {
margin:0;
padding:10px 0;
}
.docSummary {
padding:0;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
font-style:normal;
}
div.block {
font-size:14px;
font-family:'DejaVu Serif', Georgia, "Times New Roman",
Times, serif;
}
td.colLast div {
padding-top:0px;
}
td.colLast a {
padding-bottom:3px;
}
/*
Formatting effect styles
*/
.sourceLineNo {
color:green;
padding:0 30px 0 0;
}
h1.hidden {
visibility:hidden;
overflow:hidden;
font-size:10px;
}
.block {
display:block;
margin:3px 10px 2px 0px;
color:#474747;
}
.deprecatedLabel, .descfrmTypeLabel, .memberNameLabel,
.memberNameLink,
.overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel,
.returnLabel,
.seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel,
.typeNameLink {
font-weight:bold;
}
.deprecationComment, .emphasizedPhrase, .interfaceName {
font-style:italic;
}
div.block div.block span.deprecationComment, div.block
div.block span.emphasizedPhrase,
div.block div.block span.interfaceName {
font-style:normal;
}
div.contentContainer ul.blockList li.blockList h2{
padding-bottom:0px;
}
Commenting guidelines
Documenting Your Classes and Methods
It is important always to document your code clearly. For Java
programmers, some general commenting conventions have been
established by a tool called javadoc (Links to an external
site.)Links to an external site., the Java API documentation
generator. This tool can automatically extract documentation
comments from source code and generate HTML class
descriptions, like those in the Sofia API (Links to an external
site.)Links to an external site.. This tool is so popular and so
commonly used that it has set the standard for how people
document the externally visible features in their Java code. (See
the Sun article on "How to Write Doc Comments for the
Javadoc Tool" (Links to an external site.)Links to an external
site..)
JavaDoc (Links to an external site.)Links to an external site.
Comments
The javadoc tool expects comments to be written in a particular
way--other comments are ignored. JavaDoc comments (also
called just "doc comments") always start with "/**" and end
with "*/". Any other comments are ignored when generating
documentation for your code. Further, a JavaDoc comment
describing something always appears immediately before the
thing it documents.
Within a JavaDoc comment, special tags can be embedded to
signal particular kinds of information. These doc tags enable
complete, well-formatted API documentation to be
automatically generated from your source code. All JavaDoc
tags start with an at-sign (@).
If you already know some HTML, you can even embed simple
HTML markup inside your JavaDoc comments, and it will
appear in the generated documentation for your classes. This is
handy if you want to add bullet lists in a class description, or
wish to make part of your comment stand out in boldface, and
so on.
Describing a Class
You should place a descriptive JavaDoc comment just before
the start of each class you write:
/**
* Write a one-sentence summary of your class here.
* Follow it with additional details about its purpose, what
abstraction
* it represents, and how to use it.
*
* @author Stephen Edwards (stedwar2)
* @version 2011.01.30
*/
public class UserProfile
. . .
{
. . .
}
Class descriptions typically use two tags: @author indicates
who wrote the file, and @version indicates the "version" of this
file or project. You can use your full name, or just PID, in an
@author tag. In this course, it is fine to use the date when the
file was written as the version information in the @version tag.
When using tags like @author and @version, make sure to put
them at the beginning of the line within the doc comment.
For the @author line be sure to list your user name (PID) as
well as your first and last name. Also, if you started off with a
default comment generated by the IDE (like the example above)
don't forget to replace the text inside the comment with your
own. The javadoc tool will use the very first sentence of your
comment as a one-sentence summary of your class, and will use
the entire text of your comment as the full class description.
Remember that if you just write regular comments, they won't
be recognized as "official" descriptive text for document
generation:
// This comment describes what this class does, but because it
// uses //, it won't be recognized as a JavaDoc comment.
public class UserProfile
. . .
{
. . .
}
Documenting a Method
You should place a descriptive JavaDoc comment just before
each method or constructor you write:
/**
* Move the robot forward to the next HTML heading.
*/
public void advanceToNextHeading()
{
. . .
}
As with other JavaDoc comments, make sure this appears just
before the method it describes. For methods that have
parameters, you should also include a brief description of what
each parameter means. For example, we might have a
UserProfile class that provides a setter method for its name:
/**
* Set the profile's name to the given value.
*
* @param newName The new name for this profile.
*/
public void setName(String newName)
{
. . .
}
Here, a @param tag has been used to give a description of the
meaning and use of the parameter. Use a separate @param tag
to describe each parameter in the method (or constructor). Be
sure to start these tags at the beginning of a comment line, and
group all of the tags with the same name together (i.e., all
@param tags should be next to each other).
Again, javadoc will take the first sentence in your comment as a
one-sentence summary of what the method does. The remainder
of the comment will be used in generating a full description of
the method.
Some methods have return values--that is, they give back
information to their caller. For example, a getName() method
might return a String containing the user profile's current name.
You can document what information is returned using a @return
tag:
/**
* Get this profile's name.
*
* @return This profile's name
*/
public String getName()
{
. . .
}
Generating Your Documentation
Within an Eclipse project, you can use the Project->Generate
Javadoc... command to generate full documentation for your
own project straight from your source code. Click Next twice,
and in the final screen check to "Open generated index file in
browser" near the bottom. Once complete, a new tab will open
showing all of the generated documentation for your classes.
Other Comments in Your Code
JavaDoc comments are "public" documentation of the externally
accessible features of your classes. Often, you may also wish to
include "internal" (that is, private) documentation that is only
useful to someone reading the source code directly. Any
comment that does not begin with /** is treated as private,
purely for someone with access to the source code. You are free
to use such comments where ever you like to improve the
readability of your code, but ...
Internal Comments Are the Documentation Technique of Last
Resort
Choose all names carefully so that a naïve reader's first
interpretation will always be right. Do not choose names that
might mislead someone about what a method is supposed to do,
or what information a variable holds. Choosing poor names or
convoluted logic structure and then trying to explain it in
lengthy comments does little to improve readability. This is
doubly true for methods, because half the time a reader will see
your method name where it is called, not when they are reading
your method itself. If it is not immediately clear what the
method should do, that affects the readability of all the code
calling this method, no matter how many comments you put in
the method itself.
Strive to write code that is clear and understandable on its own,
simply by virtue of the names you have chosen and the structure
you use. If you feel you have to add an internal comment to
explain something, ask yourself what needs explaining. If you
need to explain what a name refers to or how you intend to use
it, consider choosing a better name. If you have to explain a
complex series of if statements or some other convoluted
structure, ask yourself (or a TA) if there is a better way. Only
after considering these alternatives should you add descriptive
comments.
Redundant Comments Are Worse Than No Comments
Consider these comments:
user = new UserProfile(); // Create a new user profile
x = x + 1; // Add one to x
user.setName("Ben"); // change the profile name
These are examples of useless comments. Many students add
comments to their code just to "make sure everything is
documented," or because they believe copious comments are
what the instructor is looking for. Comments like this just get in
the way of reading the code, however. You should only add
comments when they express something that isn't already
evident from the code itself. Comments are more information
that the poor reader has to wade through, so you need to
carefully balance their benefits against the cost of having to
read them. This reader might be - and often will be - you, so a
good mental model to adopt is that you are writing comments as
messages to your future self. This future you will be more
experienced than the current you when it comes to
programming, but will have forgotten the details of the code
written even a week ago. You should write your comments with
an eye towards minimizing the mental effort this future you has
to expend to be able to understand and maintain your code.
META-INF/MANIFEST.MF
Manifest-Version: 1.0
Implementation-Title: Tetris 5044
Permissions: sandbox
Codebase: *
JavaFX-Version: 8.0
Class-Path:
Created-By: JavaFX Packager
Implementation-Vendor:
Main-Class: edu.vt.cs5044.tetris.Tetris5044
edu/vt/cs5044/tetris/AI.classpackage edu.vt.cs5044.tetris;
publicabstractinterface AI {
publicabstract Placement findBestPlacement(Board, Shape);
publicabstract int getMaximumBlockHeight(Board);
publicabstract int getTotalBlockCount(Board);
publicabstract int getTotalGapCount(Board);
publicabstract int getColumnHeightVariability(Board);
}
edu/vt/cs5044/tetris/Board.classpackage edu.vt.cs5044.tetris;
publicsynchronizedclass Board {
publicstaticfinal int WIDTH = 10;
publicstaticfinal int HEIGHT = 24;
publicstaticfinal int HEIGHT_LIMIT = 20;
privatefinal java.util.Set blockSet;
public void Board();
Board getCopy();
publictransient void Board(String[]);
private boolean isCollision(Piece, Coordinate);
public boolean isBlockAt(int, int);
public Board getResultBoard(Shape, Placement);
void clear();
boolean isValidMove(Placement, Piece);
java.util.Set getBlockSet();
void addBlocks(java.util.Set);
private boolean isRowFilled(int);
private void shiftRowsDownTo(int);
int clearRows();
public String toString();
public boolean equals(Object);
public int hashCode();
}
edu/vt/cs5044/tetris/Box$1.classpackage edu.vt.cs5044.tetris;
synchronizedclass Box$1 extends
javafx.beans.binding.ObjectBinding {
void Box$1(Box);
protected Number computeValue();
}
edu/vt/cs5044/tetris/Box$2.classpackage edu.vt.cs5044.tetris;
synchronizedclass Box$2 extends
javafx.beans.binding.ObjectBinding {
void Box$2(Box);
protected Number computeValue();
}
edu/vt/cs5044/tetris/Box$3.classpackage edu.vt.cs5044.tetris;
synchronizedclass Box$3 extends
javafx.beans.binding.ObjectBinding {
void Box$3(Box);
protected Number computeValue();
}
edu/vt/cs5044/tetris/Box.classpackage edu.vt.cs5044.tetris;
synchronizedclass Box extends javafx.scene.shape.Rectangle {
privatefinal Coordinate coord;
privatefinal GameManager manager;
void Box(GameManager, Coordinate);
Coordinate getCoordinate();
}
edu/vt/cs5044/tetris/Coordinate.classpackage
edu.vt.cs5044.tetris;
finalsynchronizedclass Coordinate {
privatefinal int x;
privatefinal int y;
static Coordinate at(int, int);
private void Coordinate(int, int);
int getX();
int getY();
Coordinate shiftLeft();
Coordinate shiftRight();
Coordinate shiftUp();
Coordinate shiftDown();
Coordinate relativeTo(Coordinate);
public String toString();
public boolean equals(Object);
public int hashCode();
}
edu/vt/cs5044/tetris/GameManager$1.classpackage
edu.vt.cs5044.tetris;
synchronizedclass GameManager$1 {
static void <clinit>();
}
edu/vt/cs5044/tetris/GameManager.classpackage
edu.vt.cs5044.tetris;
synchronizedclass GameManager {
privatefinal javafx.scene.layout.Pane gamePane;
privatefinal javafx.scene.layout.Pane innerPane;
privatefinal Board board;
privatefinal java.util.Map boxMap;
privatefinal InfoPane infoPane;
privatefinal ScorePane scorePane;
privatefinal javafx.animation.Timeline dropTimeline;
private boolean readyToPlay;
private UserPlacement placement;
private AI brain;
private boolean brainActive;
privatefinal javafx.beans.property.SimpleIntegerProperty
pcountProp;
privatefinal javafx.beans.property.SimpleIntegerProperty
rclearProp;
private int speedLevel;
private boolean turboMode;
private RandomMode randomMode;
private ShapeStream shapeStream;
void GameManager(javafx.scene.layout.Pane, Board);
final void gameOver();
javafx.scene.layout.Pane getParentPane();
void addBlocks(java.util.Set);
final void placeNextPiece();
void start();
javafx.beans.property.SimpleIntegerProperty
getPcountProp();
javafx.beans.property.SimpleIntegerProperty
getRclearProp();
private void startDropTimer();
}
edu/vt/cs5044/tetris/InfoPane$1.classpackage
edu.vt.cs5044.tetris;
synchronizedclass InfoPane$1 extends
javafx.beans.binding.DoubleBinding {
void InfoPane$1(InfoPane, javafx.scene.text.Text);
protected double computeValue();
}
edu/vt/cs5044/tetris/InfoPane.classpackage edu.vt.cs5044.tetris;
synchronizedclass InfoPane extends
javafx.scene.layout.StackPane {
void InfoPane();
void setup(GameManager);
void show();
void hide();
}
edu/vt/cs5044/tetris/Piece.classpackage edu.vt.cs5044.tetris;
synchronizedclass Piece {
privatefinal Shape shape;
privatefinal Rotation rotation;
privatefinal int minX;
privatefinal int maxX;
privatefinal int minY;
privatefinal int maxY;
privatefinal java.util.Set blockSet;
void Piece(Shape, Rotation);
Piece nextRotation();
Shape getShape();
Rotation getRotation();
java.util.Set getBlocks();
int getWidth();
int getMaxX();
int getMinX();
int getMaxY();
int getMinY();
public boolean equals(Object);
public int hashCode();
public String toString();
}
edu/vt/cs5044/tetris/Placement.classpackage
edu.vt.cs5044.tetris;
publicsynchronizedclass Placement {
privatefinal Rotation rotation;
privatefinal int column;
public void Placement(Rotation, int);
public Rotation getRotation();
public int getColumn();
public String toString();
public boolean equals(Object);
public int hashCode();
}
edu/vt/cs5044/tetris/RandomMode$1.classpackage
edu.vt.cs5044.tetris;
synchronizedclass RandomMode$1 {
static void <clinit>();
}
edu/vt/cs5044/tetris/RandomMode.classpackage
edu.vt.cs5044.tetris;
publicfinalsynchronizedenum RandomMode {
publicstaticfinal RandomMode NORMAL;
publicstaticfinal RandomMode TEST1;
publicstaticfinal RandomMode TEST2;
publicstaticfinal RandomMode TEST3;
publicstaticfinal RandomMode TEST4;
privatefinal int value;
publicstatic RandomMode[] values();
publicstatic RandomMode valueOf(String);
private void RandomMode(String, int, int);
RandomMode next();
int getValue();
publicstatic java.util.Set getTestSet();
static void <clinit>();
}
edu/vt/cs5044/tetris/Rotation$1.classpackage
edu.vt.cs5044.tetris;
synchronizedclass Rotation$1 {
static void <clinit>();
}
edu/vt/cs5044/tetris/Rotation.classpackage edu.vt.cs5044.tetris;
publicfinalsynchronizedenum Rotation {
publicstaticfinal Rotation NONE;
publicstaticfinal Rotation CCW_90;
publicstaticfinal Rotation CCW_180;
publicstaticfinal Rotation CCW_270;
privatefinal int value;
publicstatic Rotation[] values();
publicstatic Rotation valueOf(String);
private void Rotation(String, int, int);
int getValue();
Rotation getNext();
static void <clinit>();
}
edu/vt/cs5044/tetris/ScorePane$1.classpackage
edu.vt.cs5044.tetris;
synchronizedclass ScorePane$1 extends
javafx.beans.binding.ObjectBinding {
void ScorePane$1(ScorePane, GameManager);
protected String computeValue();
}
edu/vt/cs5044/tetris/ScorePane$2.classpackage
edu.vt.cs5044.tetris;
synchronizedclass ScorePane$2 extends
javafx.beans.binding.DoubleBinding {
void ScorePane$2(ScorePane, javafx.scene.text.Text);
protected double computeValue();
}
edu/vt/cs5044/tetris/ScorePane.classpackage
edu.vt.cs5044.tetris;
synchronizedclass ScorePane extends
javafx.scene.layout.StackPane {
void ScorePane();
void setup(GameManager);
void show();
void hide();
}
edu/vt/cs5044/tetris/Shape.classpackage edu.vt.cs5044.tetris;
publicfinalsynchronizedenum Shape {
publicstaticfinal Shape I;
publicstaticfinal Shape O;
publicstaticfinal Shape T;
publicstaticfinal Shape J;
publicstaticfinal Shape L;
publicstaticfinal Shape S;
publicstaticfinal Shape Z;
privatefinal java.util.List coordSetList;
privatefinal java.util.Set rotationSet;
publicstatic Shape[] values();
publicstatic Shape valueOf(String);
privatetransient void Shape(String, int, java.util.List[]);
public java.util.Set getRotationSet();
public int getWidth(Rotation);
int countOrientations();
java.util.Set getBlocks(int);
static void <clinit>();
}
edu/vt/cs5044/tetris/ShapeStream.classpackage
edu.vt.cs5044.tetris;
publicsynchronizedclass ShapeStream {
privatefinal java.util.Random random;
public void ShapeStream(RandomMode);
public Shape nextShape();
}
edu/vt/cs5044/tetris/Tetris5044.classpackage
edu.vt.cs5044.tetris;
publicsynchronizedclass Tetris5044 extends
javafx.application.Application {
public void Tetris5044();
public void start(javafx.stage.Stage) throws Exception;
publicstatic void main(String[]);
}
edu/vt/cs5044/tetris/Tetris5044Launcher$1.classpackage
edu.vt.cs5044.tetris;
finalsynchronizedclass Tetris5044Launcher$1 extends
javafx.beans.binding.ObjectBinding {
void Tetris5044Launcher$1(javafx.stage.Stage);
protected javafx.geometry.Insets computeValue();
}
edu/vt/cs5044/tetris/Tetris5044Launcher.classpackage
edu.vt.cs5044.tetris;
synchronizedclass Tetris5044Launcher {
void Tetris5044Launcher();
static void launch(javafx.stage.Stage);
}
edu/vt/cs5044/tetris/UserPlacement.classpackage
edu.vt.cs5044.tetris;
finalsynchronizedclass UserPlacement extends
javafx.scene.Group {
privatefinal GameManager manager;
privatefinal Board board;
privatefinal java.util.Set boxSet;
private Piece piece;
private Coordinate coord;
void UserPlacement(GameManager, Board, Piece,
Coordinate);
Piece getPiece();
private boolean isBoardCollision(Piece, Coordinate);
void lockIntoBoard();
void rotate();
void applyMove(Placement);
void toColumn(int);
void shiftLeft();
void shiftRight();
boolean shiftDown();
void forceUp();
final void createBoxes();
}
edu/vt/cs5044/tetris/package-info.classpackage
edu.vt.cs5044.tetris;
interface package-info {
}
Project 3 - Play Tetris
Overview
Tetris (Links to an external site.)Links to an external site. was
arguably the most popular single-player computer game of all
time by the early 1990's. It's incredibly simple and fun to play,
and even to this day it's widely considered to be among the best
games of all time.
In case you've never seen it, the game consists of a 10-unit wide
by 24-unit tall well, into which randomly-selected geometric 4-
unit pieces begin to fall one at a time. The player manipulates
each piece as it falls, by moving it horizontally within the well,
and rotating it in 90° increments. Once the piece can fall no
further, it becomes locked in place, taking up space in the well.
However, if the player forms one or more full horizontal (10-
unit by 1-unit) rows, those rows are removed, with all rows
above shifting downward. The goal is to continue playing as
long as possible, so the player must attempt to pack the pieces
strategically. Eventually, though, the well fills upward to a
limit line, and if any portion of a piece is locked in place above
this line, the game is over.
You'll see all of this in action soon enough, and it's actually
quite easy to understand once you've played it for just a few
minutes.
Requirements
Building a full-functional Tetris application requires a little
more Java than what we've covered yet this term, so you'll be
provided a working application that you can download and
play. It's a somewhat simplified version, with a very
rudimentary scoring mechanism, but it's still just as enjoyable
and challenging as the original.
So, if the application is already provided, what is this
assignment all about? The goal here is to develop a basic
Artificial Intelligence ("AI") system, capable of controlling the
game as if it were the player.
Implementing an Interface
In previous assignments, you were given a class file with
method declarations, Javadoc comments, and placeholder
implementations. In this assignment, you'll be given an
interface instead. An interface contains the method declarations
and the Javadoc comments, but no code at all (not even
placeholders). Your task is to implement this interface, which
means you'll develop a class that provides code for all the
methods declared in the interface. In addition to the methods
specified by the interface, you will likely need to develop
several private helper methods in order to fully implement it
without redundancies.
System Description
The interface you will implement is called
edu.vt.cs5044.tetris.AI and your implementation class must be
called edu.vt.cs5044.TetrisAI. You will need to develop the
code needed to implement the methods defined by the interface.
One of the methods will be the overall AI system. This method
receives some parameters, defining the current state of the game
board and the shape to be placed, and will need to find the
"best" placement for that shape. The other methods are
responsible for intermediate calculations. These methods would
normally be private, and not specified by the interface, but for
academic purposes we're exposing these methods to ease the
testing requirements. Speaking of tests, your JUnit test file
must be called edu.vt.cs5044.TetrisAITest.
Downloads
tetris5044.jar library file containing all the compiled game
engine classes
tetris5044-api.jar library file containing the Javadocs for the
game engine
Setting up Eclipse
Download the provided files to your computer, and place them
in a convenient folder. Open Eclipse and create a new Java
Project for this assignment. Right-click the project and select
Build Path | Configure Build Path, then select the Libraries tab.
Click Add External JARs and navigate to where you placed the
downloaded JAR files, select tetris5044.jar, and click OK. You
should now see that file listed just above the JRE System
Library. Now click the little triangle to expand the new file,
select Javadoc location: (None), and click the "Edit..." button.
Here be sure to select "Javadoc in archive" first, then click
Browse. Navigate again, this time selecting tetris5044-api.jar,
and click Validate. It should tell you the location is likely
valid, so click OK, then OK, then OK to get back to your
project. Your should see a new Referenced Libraries section,
which you can expand to see the tetris5044.jar file.
Shall We Play a Game? (better than tic-tac-toe)
At this point, you can right-click your project and select Run As
| Java Application to play Tetris! Go ahead and try it now...
A window should appear with an empty game board and a
prompt to type P to play. Once you type P, you will see a new
random piece near the top, slowly falling toward the bottom of
the well. There are several alternative keyboard controls you
can use, but for now just type J and L to move the piece left and
right, and type I to rotate the piece. Once the piece is situated
as you wish, you can use K or the space bar to drop the piece
immediately, or you can just enjoy watching the piece fall
gently into place.
Zombie (brains?)
You can type '?' into the game at any time to produce a listing
in the Eclipse console of all of the available options and
keyboard controls. Some of these options will be extremely
useful during the assignment. Try that now. You'll probably
notice some interesting options, including a way to enable the
Player AI by typing Ctrl-P. When you enable this mode, just
before a new shape appears in the game, the AI is asked how to
best rotate then position the shape. Go ahead and attempt that
now. Nothing will happen, except you'll see a warning in the
console that your implementation couldn't be found, which is
perfectly understandable at this point.
Trying to Take Over the World (no, not that Brain)
Close the game for a moment now, while we get some of the
basics for the code in place. First, create a new package in your
src folder called edu.vt.cs5044 then right-click within that
package select New Class. Before you enter the class name,
click the "Add..." button to the right of the Interfaces section.
In the search box at the top, type AI and you should soon see
the AI interface (in the edu.vt.cs5044.tetris package) selected.
Click Ok to add that interface, and now you can enter the class
name TetrisAI and click Finish.
Notice that the new file declaration says public class TetrisAI
implements AI. This is what tells Java that we intend to be
compatible with any system that can work with the AI
interface. You'll also notice Eclipse is already showing an error
on the class declaration line. Click the tiny red X in the margin
and double-click "Add unimplemented methods" from the pop-
up. This asks Eclipse to generate all the method placeholders
for you! Save the file, and check out your implementation. It's
already compatible with the game system, even though all it
does is return placeholders. That's not very useful, of course,
but it's actually enough to get started. Let's see if it's
recognized by the game engine.
Launch the application again, type Ctrl-P to activate the Player
AI, and confirm that the console says the Player AI is now on.
If so, go ahead and type P to start the game. Well, that's not
very exciting. The console just keeps saying that the AI
selected an invalid move for each shape, and we still have to
manually place the pieces. That's fair enough, since all we have
are placeholders that Eclipse generated for us, but at least we
know the game found our AI and seems to be communicating
with it. Close the game again now so we can code a little more.
Let's at least provide a valid suggestion, even if it's always
exactly the same suggestion. In the findBestPlacement()
method, let's replace the placeholder:
return null;
with this:
return new Placement(Rotation.NONE, 0);
Eclipse will complain that it doesn't know about the Rotation
class yet, so again click the tiny X in the margin and double-
click to import the Rotation class from the edu.vt.cs5044
package. That should resolve the error, so save your file again.
This really doesn't seem like much of an improvement, but we'll
try it anyway.
Launch the game and use Ctrl-P then P to check it out. So, now
it's just placing everything against the left edge (column 0)
without any rotation, which is still fairly lame, but it's clear that
our AI is actually placing the pieces automatically for us!
Things can only get better from here. Close the game once
you're ready to code again.
Need More Input (accidental AI, maybe)
Obviously we need to examine the shape and the state of the
board in order to make some reasonable decisions. Let's take a
look at all those Javadocs that make up the API. In your source
file click within the word AI of "implements AI" and type Shift-
F2. This should open the Javadocs for the AI interface using an
internal browser within Eclipse. You can set it to use an
external browser, if you prefer, but this is fine for now.
Reading the Javadocs, click the findBestPlacement() method
and you'll see it actually provides a brief outline of a strategy.
We apparently need to iterate over each possible rotation, and
for each rotation we need to iterate over every possible column
placement. For each of these, we need ask the Board object to
tell us what the result of any hypothetical move would be.
Click the method Board.getResultBoard() to see how that
works. The Javadocs say that the original board instance is not
modified, and we'll get a new board instance that we can
examine.
That will meet our needs, but how do we examine one of these
hypothetical results? There are only a few other methods
available in the Board class. One provides a human-readable
rendering of the board, which might prove very useful to
visualize what's happening while debugging, and another
promising method seems to let us query any location within the
board to see which locations are occupied by fixed blocks.
There are also some static constants that tell us the overall size
of the board, plus two constructors. One of the constructors
allows us to generate arbitrary board configurations, which is
exactly what we'll need in order to create some nice test cases.
Click the Package link at the very top of any Javadoc page to
see the package overview, then navigate throughout the various
pages to see what each class and enum can do, along with the
requirements for the interface. A fundamental part of this
assignment is to learn how to use Javadocs to explore unknown
libraries, as well as to see how a somewhat larger scale system
is divided into multiple classes, each with its own purpose.
Note that class Tetris5044 is for internal use only; you won't
need it at all. Also, classes RandomMode and ShapeStream are
only needed for the optional "challenge" section below.
Strategy Games
There's no such thing as a perfect Tetris strategy, so we won't
even try. We are necessarily taking the heuristic (Links to an
external site.)Links to an external site. approach to this
problem, and there will necessarily be trade-offs involved. In
every placement decision, there are advantages and
disadvantages. How can we hope to find the "best" placement?
Now is probably a good time to look at those other methods in
the interface.
Costs and Benefits
From the API, it seems the remaining methods of the interface
are related to making some measurements to evaluate a board
position. The idea here is that we'll compute four distinct
"cost" scores, or factors, which tell our system something about
how bad (or good) a particular placement might be. We'll need
to develop those method first, before we can hope to have a
working AI system.
We're still focusing on TDD, so start with some fairly
straightforward test cases to ensure the individual scoring
methods work. Just construct a test board object, then assert
the cost score you expect your implementation to compute.
Once all of your individual cost scoring methods are working
properly as expected, its time to put it all together. The
findBestPlacement() method will need to iterate through all the
possible placements, and for each it will combine these
individual cost scores in a weighted sum, then choose the lowest
cost to return to the game engine. The weightings are important
so that certain factors can have more influence on the overall
decision than others. At first you can just set all the weights to
1, by simply summing the individual scores together, even
though eventually we'll need to adjust the weights to achieve
better results.
Strategic Default
Luck plays a starring role in Tetris. Even with the best of
strategies, it's critical to recognize that some games simply
provide a more fortunate sequence of shapes than others. Thus
it can be difficult to objectively judge exactly how good a
particular strategy might be. To help with this, our
implementation provides a set of 4 repeatable test sequences we
can use as a benchmark. The average number of pieces placed
from these 4 test sequences will act as a very reasonable metric
of how well our strategy is working overall.
Teaching to the Test
Eventually we'll be making a linear combination of our four
scores, which just means we multiply each score by some
weight, then add the weighted scores. The equation is very
straightforward:
overallCost = weight1*score1 + weight2*score2 +
weight3*score3 + weight4*score4
Computing the individual scores really isn't too bad, but what
about the weights? As noted above, we can start by simply
setting all the weights to 1, and indeed that strategy will place
an average of just above 100 pieces for each of the provided test
sequences.
Standards of Learning
Can we do better? Sure! As a start, reasonable weight ranges
for the selected factors will be 0 through 15. You can just use
trial-and-error if you wish; watch your AI play the test games
and try to figure out which factors need more or less emphasis.
For example, if your AI is creating too many unnecessary gaps,
try to increase the weight of the gap count score. Be sure to use
Turbo mode and all the Random TEST modes.
Your AI must be able to place at least 200 pieces, on average,
across the provided test sequences. Try adjusting your weights
in increments of 5, meaning weight values of 0, 5, 10, and 15.
Of the 256 possible combinations of 0, 5, 10, and 15 as weights,
about 10% will result in this level of performance. You don't
need to provide a JUnit test to demonstrate this performance,
but Web-CAT will check whether your system meets this
minimum or not.
More than Full Coverage
Unlike in the previous assignment, creating JUnit tests to cover
all of your code will be very straightforward, since there aren't
very many branches involved in the solution. You can likely
achieve full coverage with just one well-designed test case that
asserts something about each method. As a result, complete
coverage is not nearly enough to ensure you have correctly
implemented your code. Therefore, you must generate at least 5
test cases for each interface method, with non-trivial tests and
non-trivial assertions. You can satisfy this by creating at least
5 distinct test boards to be shared among assertions involving
all methods. Just be sure the test boards cover a reasonably
wide range of scenarios. Note that Web-CAT won't (and can't)
enforce this requirement, but the human grader will definitely
be looking for this.
Functional Decomposition
Judicious use of helper methods can significantly reduce the
overall amount of code you need to develop. For example, you
might want to create a helper method that returns the height of
one specified column. You can then call that method from
within a loop of all columns, and use the return value to help
compute some of the cost factors your. Your code will be
inspected during the human review for redundancies, so be sure
to develop helper methods wherever appropriate.
Automating the Automation
You might have noticed that it can get somewhat tedious to try
every combination of 0, 5, 10, and 15 for each of the weights,
even in Turbo mode. You might have also noticed that you've
been given sufficient tools to run entire simulated games
without the user interface at all.
As a challenge, see if you can identify the very best
combination of 0, 5, 10, and 15 weights, by writing a separate
class file called edu.vt.cs5044.WeightFinder with its own
main() method. This file will be completely ignored by Web-
CAT, and you don't need to generate any tests for it at all.
You'll also need to add a public method, such as setWeights(int
w1, int w2, int w3, int w4) to your TetrisAI implementation, to
apply the various weight combinations. This method will need
to be exercised by a single assert, just to be sure it's covered
within your own JUnit tests.
Once you've found the optimum combination, you'll need to
hard-code those values back into your AI as the defaults, in
order to watch them in action. The best weights among these
combinations will place an average of over 480 pieces for the
test sequences. That's quite an improvement, unless you
happened to get very lucky in your trial and error phase!
Confirm that this is all working as expected, and that you're
placing 480+ pieces on average for the test sequences before the
next part of the challenge. It should be a simple change to your
code to try stepping by 3 instead of 5 (meaning you should test
every combination of 0, 3, 6, 9, 12, and 15 for every weight).
This process takes about 5-10 times longer to run than stepping
by 5. However, if everything was already working properly,
you'll only need to do this once, and you'll discover that your
newly-tuned weights will average over 1,900 pieces placed for
the test sequences. We'll call that a definite win!
Still not satisfied? You can always try stepping by 1 instead.
Again it's a trivial code change, but note that this process takes
about 50-100 times longer to run than stepping by 3, so we're
likely talking about a few hours at this point. However, your
newly-optimized AI possess the astonishing capability of
averaging over 6,100 pieces placed for the test sequences! You
might be somewhat amazed when you discover the optimum
weightings. Also, you're in for a bit of a surprise when you
watch this in action, specifically comparing the results of the
TEST1 sequence to those of the TEST2 sequence.
If you make any progress with this OPTIONAL challenge,
please add a brief write-up in the comments of your
WeightFinder class, just to let us know what you did, along with
any thoughts you'd like to share about the experience. Of
course you may also discuss this in Piazza, although please
don't post your code (or any weightings you find) to the entire
class, so as not to spoil the fun for anyone else.
Hopefully you enjoyed this challenge!
Submit to Web-CAT
Submit your solution to Web-CAT (Links to an external
site.)Links to an external site. via Eclipse or the web interface.
Please feel free to improve and resubmit your code as many
times as you like (before the deadline) in order to improve your
score.
Important Notes:
· Your submission will be evaluated both by Web-CAT (40
points) and by human (40 points). As such, Web-CAT's
automated score will show at most 40/80 points.
· Your JUnit test class will be evaluated by Web-CAT to ensure
complete coverage of you implementation code, but it will NOT
be evaluated for style. Web-CAT will also use its own internal
test suite (that we've developed) to evaluate your system.
· Carefully review your feedback. In the summary, you will see
a table listing each of your source files with a green/red bar by
each non-test file. If the bar for any file is not completely
green, then some code in that file was not exercised by your
own tests. Click the file name to view your source code and
look for lines that are highlighted in a pink color. Hover your
mouse over highlighted lines for additional information. You
will need to add at least one test case to exercise the highlighted
code. This includes testing the same actions you've already
tested, but starting from different initial conditions.
· See the program grading rubric for full details on the grading
criteria applied to this assignment.
CS 5044
Object-Oriented Programming with Java
Q&A Session
Midterm Exam
• Exam is split into three parts, all due Monday (7/3) at noon ET
– Each part has a 30 minute time limit for 20 multiple-choice
questions
– Each part covers a cross-section of all materials from Module
1 through Module 5
– See also Piazza @166 (and posts linked from there) for a few
more details
Project 3 - Play Tetris
• Tetris!
– We've been tasked to develop an artificial intelligence (AI)
that can play Tetris
• An "interface" has been provided; you will implement the
interface
– We'll learn more about interfaces in several weeks, but for
now:
• An interface is just a way in Java to specify required methods,
without any code
• To implement the interface, we develop a class with actual
code in these methods
– Eclipse can generate the placeholder methods for us
automatically
• Once that's done, it becomes just like our previous projects
• Plus, the compiler will ensure we don't accidentally change
the method headers
Meet the Cast of Players
• enum Shape
– One value for each of the seven geometric pieces involved:
– Each Shape provides a set of distinct Rotation values (default
orientations shown above)
– You can also request the width of the shape (in blocks) after
applying any valid Rotation
• enum Rotation
– One value for each 90° rotation:
• NONE
• CCW_90
• CCW_180
• CCW_270
Game On
• class Placement
– A Placement just holds a Rotation value and a column number
together
– This is what our AI needs to return to the game engine, for
any Shape:
• First the Rotation will be applied to the Shape
• Then the rotated Shape will be moved horizontally
– The left-most block will be placed in the specified column
– Invalid Placement objects will be rejected (and ignored) by
the game engine
• class Board
– Represents the state of the playing board at any given time
– Provides static int values: WIDTH, HEIGHT, and
HEIGHT_LIMIT
– Contains a collection of fixed blocks; allows us to query via
isBlockAt(col, row)
– We can ask the board to show us the hypothetical result of
placing another piece
• The piece will be placed and dropped, then any full rows will
be cleared
• Creates a new Board object; does not mutate the existing
Board
– We can also construct new Board objects with arbitrary blocks
for testing
• ShapeStream and RandomMode are only used for the optional
challenge
• Tetris5044 is for internal use only, by the game engine itself
Mind Games
• interface AI
– This is what we need to implement!
– public Placement findBestPlacement(Board currentBoard,
Shape shape)
• This is how the game engine asks our AI what to do
– The remaining methods need to compute "cost" factors for a
given board:
• int getColumnHeightVariability(Board board)
• int getMaximumBlockHeight(Board board)
• int getTotalBlockCount(Board board)
• int getTotalGapCount(Board board)
• Academic Note: Normally these would be private, and not
required by the interface
– The individual cost factor methods should be developed (and
tested!) first
– Once you've completed at least one cost factor method, to find
the best placement:
• For every possible placement of this shape
– Get the board that would result from this placement
– Calculate cost factors for result board and combine with
weights
– If this is the lowest overall cost so far, consider this
placement as the new best
• Return the best placement to the game engine
– Adjust the weights to meet minimum average performance
requirements in TEST modes

More Related Content

Similar to allclasses-frame.htmlAll ClassesAIBoardPlacementRandomModeRotati.docx

Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
PHP Cheat Sheet
PHP Cheat SheetPHP Cheat Sheet
Graphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLetsGraphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLetsJussi Pohjolainen
 
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdfNeed help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
fastechsrv
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
Christopher Akinlade
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
OblivionWalker
 
PHP-Cheat-Sheet.pdf
PHP-Cheat-Sheet.pdfPHP-Cheat-Sheet.pdf
PHP-Cheat-Sheet.pdf
hectoralvarogarzonbu
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Java scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java ScannerJava scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java Scanner
Edward Nyang'ali
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
Tomer Gabel
 
js_class_notes_for_ institute it is very useful for your study.pdf
js_class_notes_for_ institute  it is very useful for your study.pdfjs_class_notes_for_ institute  it is very useful for your study.pdf
js_class_notes_for_ institute it is very useful for your study.pdf
Well82
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
sujatha629799
 
Regex1.1.pptx
Regex1.1.pptxRegex1.1.pptx
Regex1.1.pptx
VigneshK635628
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
saranuru
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
info673628
 

Similar to allclasses-frame.htmlAll ClassesAIBoardPlacementRandomModeRotati.docx (20)

Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
PHP Cheat Sheet
PHP Cheat SheetPHP Cheat Sheet
PHP Cheat Sheet
 
Graphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLetsGraphics, Threads and HTTPConnections in MIDLets
Graphics, Threads and HTTPConnections in MIDLets
 
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdfNeed help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
PHP-Cheat-Sheet.pdf
PHP-Cheat-Sheet.pdfPHP-Cheat-Sheet.pdf
PHP-Cheat-Sheet.pdf
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java ScannerJava scanner, everything you need to know about Java Scanner
Java scanner, everything you need to know about Java Scanner
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
 
js_class_notes_for_ institute it is very useful for your study.pdf
js_class_notes_for_ institute  it is very useful for your study.pdfjs_class_notes_for_ institute  it is very useful for your study.pdf
js_class_notes_for_ institute it is very useful for your study.pdf
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Chapter 08
Chapter 08Chapter 08
Chapter 08
 
Regex1.1.pptx
Regex1.1.pptxRegex1.1.pptx
Regex1.1.pptx
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
 

More from simonlbentley59018

Allison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docx
Allison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docxAllison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docx
Allison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docx
simonlbentley59018
 
Allen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docx
Allen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docxAllen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docx
Allen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docx
simonlbentley59018
 
All workings, when appropriate, must be shown to substantiate your.docx
All workings, when appropriate, must be shown to substantiate your.docxAll workings, when appropriate, must be shown to substantiate your.docx
All workings, when appropriate, must be shown to substantiate your.docx
simonlbentley59018
 
All yellow highlight is missing answer, please answer all of t.docx
All yellow highlight is missing answer, please answer all of t.docxAll yellow highlight is missing answer, please answer all of t.docx
All yellow highlight is missing answer, please answer all of t.docx
simonlbentley59018
 
All models are wrong. Some models are useful.—George E. P. B.docx
All models are wrong. Some models are useful.—George E. P. B.docxAll models are wrong. Some models are useful.—George E. P. B.docx
All models are wrong. Some models are useful.—George E. P. B.docx
simonlbentley59018
 
ALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docx
ALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docxALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docx
ALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docx
simonlbentley59018
 
ALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docx
ALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docxALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docx
ALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docx
simonlbentley59018
 
All views expressed in this paper are those of the authors a.docx
All views expressed in this paper are those of the authors a.docxAll views expressed in this paper are those of the authors a.docx
All views expressed in this paper are those of the authors a.docx
simonlbentley59018
 
All Wet! Legacy of Juniper Utility has residents stewingBy Eri.docx
All Wet! Legacy of Juniper Utility has residents stewingBy Eri.docxAll Wet! Legacy of Juniper Utility has residents stewingBy Eri.docx
All Wet! Legacy of Juniper Utility has residents stewingBy Eri.docx
simonlbentley59018
 
All three of the Aristotle, Hobbes, and Douglass readings discussed .docx
All three of the Aristotle, Hobbes, and Douglass readings discussed .docxAll three of the Aristotle, Hobbes, and Douglass readings discussed .docx
All three of the Aristotle, Hobbes, and Douglass readings discussed .docx
simonlbentley59018
 
All rights reserved. No part of this report, including t.docx
All rights reserved. No part of this report, including t.docxAll rights reserved. No part of this report, including t.docx
All rights reserved. No part of this report, including t.docx
simonlbentley59018
 
All PrinciplesEvidence on Persuasion Principles This provides som.docx
All PrinciplesEvidence on Persuasion Principles This provides som.docxAll PrinciplesEvidence on Persuasion Principles This provides som.docx
All PrinciplesEvidence on Persuasion Principles This provides som.docx
simonlbentley59018
 
All papers may be subject to submission for textual similarity revie.docx
All papers may be subject to submission for textual similarity revie.docxAll papers may be subject to submission for textual similarity revie.docx
All papers may be subject to submission for textual similarity revie.docx
simonlbentley59018
 
All of us live near some major industry. Describe the history of an .docx
All of us live near some major industry. Describe the history of an .docxAll of us live near some major industry. Describe the history of an .docx
All of us live near some major industry. Describe the history of an .docx
simonlbentley59018
 
All of Us Research Program—Protocol v1.12 IRB Approval Dat.docx
All of Us Research Program—Protocol v1.12 IRB Approval Dat.docxAll of Us Research Program—Protocol v1.12 IRB Approval Dat.docx
All of Us Research Program—Protocol v1.12 IRB Approval Dat.docx
simonlbentley59018
 
All participants must read the following article ATTACHED Agwu.docx
All participants must read the following article ATTACHED Agwu.docxAll participants must read the following article ATTACHED Agwu.docx
All participants must read the following article ATTACHED Agwu.docx
simonlbentley59018
 
ALL of the requirements are contained in the attached document.  T.docx
ALL of the requirements are contained in the attached document.  T.docxALL of the requirements are contained in the attached document.  T.docx
ALL of the requirements are contained in the attached document.  T.docx
simonlbentley59018
 
All five honorees cared greatly about the success of Capella lea.docx
All five honorees cared greatly about the success of Capella lea.docxAll five honorees cared greatly about the success of Capella lea.docx
All five honorees cared greatly about the success of Capella lea.docx
simonlbentley59018
 
All of the instructions will be given to you in a document. One docu.docx
All of the instructions will be given to you in a document. One docu.docxAll of the instructions will be given to you in a document. One docu.docx
All of the instructions will be given to you in a document. One docu.docx
simonlbentley59018
 
All financial statement audits will include an audit of the inve.docx
All financial statement audits will include an audit of the inve.docxAll financial statement audits will include an audit of the inve.docx
All financial statement audits will include an audit of the inve.docx
simonlbentley59018
 

More from simonlbentley59018 (20)

Allison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docx
Allison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docxAllison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docx
Allison RogersProfessor KoenigCOMM 3313October 12th, 2018H.docx
 
Allen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docx
Allen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docxAllen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docx
Allen 1Kiah AllenProfessor HirschENG1018 Feb. 2018Defo.docx
 
All workings, when appropriate, must be shown to substantiate your.docx
All workings, when appropriate, must be shown to substantiate your.docxAll workings, when appropriate, must be shown to substantiate your.docx
All workings, when appropriate, must be shown to substantiate your.docx
 
All yellow highlight is missing answer, please answer all of t.docx
All yellow highlight is missing answer, please answer all of t.docxAll yellow highlight is missing answer, please answer all of t.docx
All yellow highlight is missing answer, please answer all of t.docx
 
All models are wrong. Some models are useful.—George E. P. B.docx
All models are wrong. Some models are useful.—George E. P. B.docxAll models are wrong. Some models are useful.—George E. P. B.docx
All models are wrong. Some models are useful.—George E. P. B.docx
 
ALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docx
ALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docxALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docx
ALL WORK MUST BE ORIGINAL, CITED, IN APA FORMAT & WILL BE SUBMITTED .docx
 
ALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docx
ALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docxALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docx
ALL WORK MUST BE ORIGINAL, CITED IN APA FORMAT AND WILL BE SUBMITTED.docx
 
All views expressed in this paper are those of the authors a.docx
All views expressed in this paper are those of the authors a.docxAll views expressed in this paper are those of the authors a.docx
All views expressed in this paper are those of the authors a.docx
 
All Wet! Legacy of Juniper Utility has residents stewingBy Eri.docx
All Wet! Legacy of Juniper Utility has residents stewingBy Eri.docxAll Wet! Legacy of Juniper Utility has residents stewingBy Eri.docx
All Wet! Legacy of Juniper Utility has residents stewingBy Eri.docx
 
All three of the Aristotle, Hobbes, and Douglass readings discussed .docx
All three of the Aristotle, Hobbes, and Douglass readings discussed .docxAll three of the Aristotle, Hobbes, and Douglass readings discussed .docx
All three of the Aristotle, Hobbes, and Douglass readings discussed .docx
 
All rights reserved. No part of this report, including t.docx
All rights reserved. No part of this report, including t.docxAll rights reserved. No part of this report, including t.docx
All rights reserved. No part of this report, including t.docx
 
All PrinciplesEvidence on Persuasion Principles This provides som.docx
All PrinciplesEvidence on Persuasion Principles This provides som.docxAll PrinciplesEvidence on Persuasion Principles This provides som.docx
All PrinciplesEvidence on Persuasion Principles This provides som.docx
 
All papers may be subject to submission for textual similarity revie.docx
All papers may be subject to submission for textual similarity revie.docxAll papers may be subject to submission for textual similarity revie.docx
All papers may be subject to submission for textual similarity revie.docx
 
All of us live near some major industry. Describe the history of an .docx
All of us live near some major industry. Describe the history of an .docxAll of us live near some major industry. Describe the history of an .docx
All of us live near some major industry. Describe the history of an .docx
 
All of Us Research Program—Protocol v1.12 IRB Approval Dat.docx
All of Us Research Program—Protocol v1.12 IRB Approval Dat.docxAll of Us Research Program—Protocol v1.12 IRB Approval Dat.docx
All of Us Research Program—Protocol v1.12 IRB Approval Dat.docx
 
All participants must read the following article ATTACHED Agwu.docx
All participants must read the following article ATTACHED Agwu.docxAll participants must read the following article ATTACHED Agwu.docx
All participants must read the following article ATTACHED Agwu.docx
 
ALL of the requirements are contained in the attached document.  T.docx
ALL of the requirements are contained in the attached document.  T.docxALL of the requirements are contained in the attached document.  T.docx
ALL of the requirements are contained in the attached document.  T.docx
 
All five honorees cared greatly about the success of Capella lea.docx
All five honorees cared greatly about the success of Capella lea.docxAll five honorees cared greatly about the success of Capella lea.docx
All five honorees cared greatly about the success of Capella lea.docx
 
All of the instructions will be given to you in a document. One docu.docx
All of the instructions will be given to you in a document. One docu.docxAll of the instructions will be given to you in a document. One docu.docx
All of the instructions will be given to you in a document. One docu.docx
 
All financial statement audits will include an audit of the inve.docx
All financial statement audits will include an audit of the inve.docxAll financial statement audits will include an audit of the inve.docx
All financial statement audits will include an audit of the inve.docx
 

Recently uploaded

Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

allclasses-frame.htmlAll ClassesAIBoardPlacementRandomModeRotati.docx

  • 1. allclasses- frame.htmlAll ClassesAIBoardPlacementRandomModeRotationS hapeShapeStreamTetris5044 allclasses- noframe.htmlAll ClassesAIBoardPlacementRandomModeRotatio nShapeShapeStreamTetris5044 constant-values.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll ClassesConstant Field Values Contentsedu.vt.* edu.vt.* edu.vt.cs5044.tetris.BoardModifier and TypeConstant FieldValuepublic static final intHEIGHT24public static final int HEIGHT_LIMIT20public static final intWIDTH10Skip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll Classes deprecated-list.html
  • 2. JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll ClassesDeprecated API ContentsSkip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll Classes edu/vt/cs5044/tetris/Tetris5044.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu.vt.cs5044.tetris
  • 3. Class Tetris5044ObjectApplicationTetris5044public class Tetris5044 extends Application The main application class; for internal use only. Version:1.0Nested Class SummaryNested classes/interfaces inherited from class Application Application.ParametersField SummaryFields inherited from class Application STYLESHEET_CASPIAN, STYLESHEET_MODENAConstructor Summary Constructors Constructor and DescriptionTetris5044() Method Summary All Methods Static MethodsInstance MethodsConcrete MethodsModifier and TypeMethod and Descriptionstatic voidmain(String[] args) For internal use only. voidstart(Stage primaryStage) For internal use only. Methods inherited from class Application getHostServices, getParameters, getUserAgentStylesheet, init, launch, launch, notifyPreloader, setUserAgentStylesheet,
  • 4. stopMethods inherited from class Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitConstructor DetailTetris5044public Tetris5044()Method Detailstartpublic void start(Stage primaryStage) throws Exception For internal use only. Specified by:start in class ApplicationParameters:primaryStage - for internal use only.Throws:Exception - for internal use only.mainpublic static void main(String[] args) For internal use only. Parameters:args - ignored.Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu/vt/cs5044/tetris/RandomMode.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Enum
  • 5. Constants | Field | MethodDetail: Enum Constants | Field | Method edu.vt.cs5044.tetris Enum RandomModeObjectEnum<RandomMode>RandomModeAll Implemented Interfaces:Serializable, Comparable<RandomMode>public enum RandomMode extends Enum<RandomMode> Enumerates the modes of randomness used for generating shapes for games of tetris. Enum Constant Summary Enum Constants Enum Constant and DescriptionNORMAL Stream of randomness that is not repeatable. TEST1 Repeatable stream of randomness number 1. TEST2 Repeatable stream of randomness, number 2. TEST3 Repeatable stream of randomness, number 3. TEST4
  • 6. Repeatable streams of randomness, number 4. Method Summary All Methods Static MethodsConcrete MethodsModifier and TypeMethod and Descriptionstatic Set<RandomMode>getTestSet() Fetch the set of all test-related values. static RandomModevalueOf(String name) Returns the enum constant of this type with the specified name. static RandomMode[]values() Returns an array containing the constants of this enum type, in the order they are declared. Methods inherited from class Enum clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOfMethods inherited from class Object getClass, notify, notifyAll, wait, wait, waitEnum Constant DetailNORMALpublic static final RandomMode NORMAL Stream of randomness that is not repeatable. TEST1public static final RandomMode TEST1 Repeatable stream of randomness number 1.
  • 7. TEST2public static final RandomMode TEST2 Repeatable stream of randomness, number 2. TEST3public static final RandomMode TEST3 Repeatable stream of randomness, number 3. TEST4public static final RandomMode TEST4 Repeatable streams of randomness, number 4. Method Detailvaluespublic static RandomMode[] values() Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (RandomMode c : RandomMode.values()) System.out.println(c); Returns:an array containing the constants of this enum type, in the order they are declaredvalueOfpublic static RandomMode valueOf(String name) Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) Parameters:name - the name of the enum constant to be returned.Returns:the enum constant with the specified
  • 8. nameThrows:IllegalArgumentException - if this enum type has no constant with the specified nameNullPointerException - if the argument is nullgetTestSetpublic static Set<RandomMode> getTestSet() Fetch the set of all test-related values. This set includes all RandomMode values except NORMAL. Returns:set of test-related values.Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Enum Constants | Field | MethodDetail: Enum Constants | Field | Method edu/vt/cs5044/tetris/package-frame.htmledu.vt.cs5044.tetris InterfacesAI ClassesBoardPlacementShapeStreamTetris5044 EnumsRandomModeRotationShape edu/vt/cs5044/tetris/Placement.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M
  • 9. ethodDetail: Field | Constr | Method edu.vt.cs5044.tetris Class PlacementObjectPlacementpublic class Placement extends Object Represents a single possible placement of a shape. The placement is specified by a rotation along with the horizontal location of the left-most block of the rotated shape Constructor Summary Constructors Constructor and DescriptionPlacement(Rotation rotation, int column) Construct a new object with the specified parameters. Method Summary All Methods Instance MethodsConcrete MethodsModifier and TypeMethod and Descriptionbooleanequals(Object obj) Test for equality with another Placement. intgetColumn() Fetch specified column.
  • 10. RotationgetRotation() Fetch specified rotation. inthashCode()StringtoString() Generates a simple human-readable representation of this object. Methods inherited from class Object clone, finalize, getClass, notify, notifyAll, wait, wait, waitConstructor DetailPlacementpublic Placement(Rotation rotation, int column) Construct a new object with the specified parameters. Parameters:rotation - number of rotations to apply to the shape.column - left-most block of the rotated shape goes in this column.Method DetailgetRotationpublic Rotation getRotation() Fetch specified rotation. Returns:rotation.getColumnpublic int getColumn() Fetch specified column. The left-most column of the board is 0. The left-most block of the rotated shape goes in the specified column. Returns:column.toStringpublic String toString()
  • 11. Generates a simple human-readable representation of this object. Overrides:toString in class ObjectReturns:simple representation of this object.equalspublic boolean equals(Object obj) Test for equality with another Placement. Two placements are equal if and only if they contain the same column and rotation values. Overrides:equals in class ObjectParameters:obj - the other placement.Returns:true if the placements are equivalent; false otherwise.hashCodepublic int hashCode()Overrides:hashCode in class ObjectSkip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu/vt/cs5044/tetris/Board.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method
  • 12. edu.vt.cs5044.tetris Class BoardObjectBoardpublic class Board extends Object Represents a Tetris game board, including all fixed blocks. This class is effectively immutable, because there are no public mutators. Field Summary Fields Modifier and TypeField and Descriptionstatic intHEIGHT Height of all game boards, in blocks. static intHEIGHT_LIMIT Height limit of all game boards, in blocks. static intWIDTH Width of all game boards, in blocks. Constructor Summary Constructors Constructor and DescriptionBoard() Construct a new empty board with no fixed blocks. Board(String... initialBlocks) Construct a new board with the specified initial blocks.
  • 13. Method Summary All Methods Instance MethodsConcrete MethodsModifier and TypeMethod and Descriptionbooleanequals(Object obj) Test for equality with another Board. BoardgetResultBoard(Shape shape, Placement place) Generate a new board that is the result of placing a shape in this board. inthashCode()booleanisBlockAt(int col, int row) Check for a fixed block at a specified location. StringtoString() Generate a multi-line ASCII art visualization of this board. Methods inherited from class Object clone, finalize, getClass, notify, notifyAll, wait, wait, waitField DetailWIDTHpublic static final int WIDTH Width of all game boards, in blocks. See Also:Constant Field ValuesHEIGHTpublic static final int HEIGHT Height of all game boards, in blocks. See Also:Constant Field ValuesHEIGHT_LIMITpublic static
  • 14. final int HEIGHT_LIMIT Height limit of all game boards, in blocks. If any block becomes fixed at or above this row index, the game ends. See Also:Constant Field ValuesConstructor DetailBoardpublic Board() Construct a new empty board with no fixed blocks. Boardpublic Board(String... initialBlocks) Construct a new board with the specified initial blocks. Specify a variable number of String values as arguments. Each String represents one row of the board. The last row is placed at the bottom of the board. No more than HEIGHT_LIMIT rows may be specified. If fewer rows are specified, the unspecified rows will be empty. Each row must have exactly WIDTH characters. The first character represents the left edge of the board. Each character must be either a space ' ' or a hash '#'. A hash means a single fixed block exists at that position. A space means no fixed block exists at that position. Parameters:initialBlocks - blocks to include in the boardMethod DetailisBlockAtpublic boolean isBlockAt(int col, int row) Check for a fixed block at a specified location.
  • 15. Parameters:col - column number; left-most column is zerorow - row number; bottom-most row is zeroReturns:true if a fixed block is at this location; false otherwisegetResultBoardpublic Board getResultBoard(Shape sh ape, Placement place) Generate a new board that is the result of placing a shape in this board. First a copy of this board is created. The shape is placed at the top of this copy, rotated according to the placement, then moved horizontally such that the left-most block is in the specified column. The block is then dropped until it locks into place, then all completely full rows (if any) are cleared as in normal play. The result of this activity is returned. Note: This method is not a mutator; it does not change this board object.Parameters:shape - the Shape to place.place - a Placement containing the rotation and location of the shape.Returns:a new Board representing the result of the placement.toStringpublic String toString() Generate a multi-line ASCII art visualization of this board. The walls of the board are represented as '*' characters above the HEIGHT_LIMIT, and as '|' characters otherwise. The bottom of the board is represented by a row of '-'
  • 16. characters. Fixed blocks are represented by '#' characters. Overrides:toString in class ObjectReturns:a rudimentary depiction of the board.equalspublic boolean equals(Object obj) Test for equality with another Board. Two boards are equal if and only if they contain the same arrangement of fixed blocks. Overrides:equals in class ObjectParameters:obj - the other board.Returns:true if the boards are equivalent; false otherwise.hashCodepublic int hashCode()Overrides:hashCode in class ObjectSkip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu/vt/cs5044/tetris/AI.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method
  • 17. edu.vt.cs5044.tetris Interface AIpublic interface AI Interface the game engine uses to communicate with AI implementations. You must develop an implementation of this interface. Method Summary All Methods Instance MethodsAbstract MethodsModifier and TypeMethod and DescriptionPlacementfindBestPlacement(Board currentBoard, Shape shape) Calculate the best placement available for a shape in a board. intgetColumnHeightVariability(Board board) Return the variability of column heights of a board (see academic note). intgetMaximumBlockHeight(Board board) Compute the maximum block height of a board (see academic note). intgetTotalBlockCount(Board board) Compute the total block count of a board (see academic note). intgetTotalGapCount(Board board) Compute the total gap count of a board (see academic note).
  • 18. Method DetailfindBestPlacementPlacement findBestPlacement(Board cu rrentBoard, Shape shape) Calculate the best placement available for a shape in a board. All possible columns for all possible rotations of the given shape should be considered. For each combination, implementations should call Board.getResultBoard(Shape, Placement) to generate the resultant board after a hypothetical placement. The implementation must calculate a relative cost value for ech resultant board, then return the Placement object associated with the lowest cost (most preferable). Parameters:currentBoard - the existing board.shape - the shape to be placed in the board.Returns:the best move as computed by the implementation.getMaximumBlockHeightint getMaximumBlock Height(Board board) Compute the maximum block height of a board (see academic note). Finds the height of the upper-most block within a board. Note that a block in row r has a height of r+1. ACADEMIC NOTE: This method would normally be declared as private. We're exposing it as public only for testing
  • 19. purposes.Parameters:board - the Board to evaluate.Returns:the height of the of block in the largest row number.getTotalBlockCountint getTotalBlockCount(Board boar d) Compute the total block count of a board (see academic note). Counts the total number of blocks residing within a board. ACADEMIC NOTE: This method would normally be declared as private. We're exposing it as public only for testing purposes.Parameters:board - the Board to evaluate.Returns:the total number of blocks.getTotalGapCountint getTotalGapCount(Board board) Compute the total gap count of a board (see academic note). Counts the number of gaps residing within a board. A gap is a location without a block, where a block exists in any higher row of the same column. ACADEMIC NOTE: This method would normally be declared as private. We're exposing it as public only for testing purposes.Parameters:board - the Board to evaluate.Returns:the number of gaps.getColumnHeightVariabilityint getColumnHeightVariabilit y(Board board)
  • 20. Return the variability of column heights of a board (see academic note). The variability is defined here as the sum of the absolute values of differences in heights of adjacent columns, as measure from either edge of the board to the other. Note that for a board width w, there are w-1 adjacent column heights. ACADEMIC NOTE: This method would normally be declared as private. We're exposing it as public only for testing purposes.Parameters:board - the Board to evaluate.Returns:the variability of column heights.Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu/vt/cs5044/tetris/package-summary.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev PackageNext Packa geFramesNo FramesAll ClassesPackage edu.vt.cs5044.tetris
  • 21. This package holds the internal components necessary for the game. See: Description Interface Summary InterfaceDescriptionAI Interface the game engine uses to communicate with AI implementations. Class Summary ClassDescriptionBoard Represents a Tetris game board, including all fixed blocks. Placement Represents a single possible placement of a shape. ShapeStream Used to generate a stream of random shapes for a game of Tetris. Tetris5044 The main application class; for internal use only. Enum Summary EnumDescriptionRandomMode Enumerates the modes of randomness used for generating shapes for games of tetris. Rotation Enumeration representing each of the four distinct rotations in Tetris. Shape Enumeration representing each of the seven distinct tetromino
  • 22. shapes. Package edu.vt.cs5044.tetris Description This package holds the internal components necessary for the game. Skip navigation linksPackageClassDeprecatedIndexHelpPrev PackageNext Packa geFramesNo FramesAll Classes edu/vt/cs5044/tetris/ShapeStream.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu.vt.cs5044.tetris
  • 23. Class ShapeStreamObjectShapeStreampublic class ShapeStream extends Object Used to generate a stream of random shapes for a game of Tetris. Constructor Summary Constructors Constructor and DescriptionShapeStream(RandomMode mode) Construct a new ShapeStream in the specified RandomMode. Method Summary All Methods Instance MethodsConcrete MethodsModifier and TypeMethod and DescriptionShapenextShape() Fetch the next random Shape from this stream. Methods inherited from class Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitConstructor DetailShapeStreampublic ShapeStream(RandomMode mode) Construct a new ShapeStream in the specified RandomMode. Parameters:mode - specifies the strategy for generating the random sequence; must not be null.Method DetailnextShapepublic Shape nextShape()
  • 24. Fetch the next random Shape from this stream. Returns:the next random Shape from this stream.Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Field | Constr | M ethodDetail: Field | Constr | Method edu/vt/cs5044/tetris/Shape.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Enum Constants | Field | MethodDetail: Enum Constants | Field | Method edu.vt.cs5044.tetris Enum ShapeObjectEnum<Shape>ShapeAll Implemented Interfaces:Serializable, Comparable<Shape>public enum Shape extends Enum<Shape>
  • 25. Enumeration representing each of the seven distinct tetromino shapes. Enum Constant Summary Enum Constants Enum Constant and DescriptionI The "I" shape. J The "J" shape. L The "L" shape. O The "O" shape. S The "S" shape. T The "T" shape. Z The "Z" shape. Method Summary All Methods Static MethodsInstance MethodsConcrete MethodsModifier and TypeMethod and DescriptionSet<Rotation>getRotationSet() Get the set of valid rotations for this shape. intgetWidth(Rotation r)
  • 26. Get the width of this shape, in blocks, after applying a specified rotation. static ShapevalueOf(String name) Returns the enum constant of this type with the specified name. static Shape[]values() Returns an array containing the constants of this enum type, in the order they are declared. Methods inherited from class Enum clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOfMethods inherited from class Object getClass, notify, notifyAll, wait, wait, waitEnum Constant DetailIpublic static final Shape I The "I" shape. Opublic static final Shape O The "O" shape. Tpublic static final Shape T The "T" shape. Jpublic static final Shape J
  • 27. The "J" shape. Lpublic static final Shape L The "L" shape. Spublic static final Shape S The "S" shape. Zpublic static final Shape Z The "Z" shape. Method Detailvaluespublic static Shape[] values() Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (Shape c : Shape.values()) System.out.println(c); Returns:an array containing the constants of this enum type, in the order they are declaredvalueOfpublic static Shape valueOf(String name) Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
  • 28. Parameters:name - the name of the enum constant to be returned.Returns:the enum constant with the specified nameThrows:IllegalArgumentException - if this enum type has no constant with the specified nameNullPointerException - if the argument is nullgetRotationSetpublic Set<Rotation> getRotationSet() Get the set of valid rotations for this shape. Returns a set of Rotation values that can be applied to this shape to result in distinct orientations. Returns:the a set of Rotation values.getWidthpublic int getWidth(Rotation r) Get the width of this shape, in blocks, after applying a specified rotation. The rotation parameter must be contained in the Set returned by getRotationSet(). Parameters:r - the rotation to apply.Returns:the width of the rotated shape, in blocks.Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Enum Constants | Field | MethodDetail: Enum Constants | Field | Method edu/vt/cs5044/tetris/Rotation.html
  • 29. JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr amesNo FramesAll ClassesSummary: Nested | Enum Constants | Field | MethodDetail: Enum Constants | Field | Method edu.vt.cs5044.tetris Enum RotationObjectEnum<Rotation>RotationAll Implemented Interfaces:Serializable, Comparable<Rotation>public enum Rotation extends Enum<Rotation> Enumeration representing each of the four distinct rotations in Tetris. Enum Constant Summary Enum Constants Enum Constant and DescriptionCCW_180 Rotate 180° counter-clockwise. CCW_270 Rotate 270° counter-clockwise.
  • 30. CCW_90 Rotate 90° counter-clockwise. NONE No rotation; the default orientation. Method Summary All Methods Static MethodsConcrete MethodsModifier and TypeMethod and Descriptionstatic RotationvalueOf(String name) Returns the enum constant of this type with the specified name. static Rotation[]values() Returns an array containing the constants of this enum type, in the order they are declared. Methods inherited from class Enum clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOfMethods inherited from class Object getClass, notify, notifyAll, wait, wait, waitEnum Constant DetailNONEpublic static final Rotation NONE No rotation; the default orientation. CCW_90public static final Rotation CCW_90 Rotate 90° counter-clockwise.
  • 31. CCW_180public static final Rotation CCW_180 Rotate 180° counter-clockwise. CCW_270public static final Rotation CCW_270 Rotate 270° counter-clockwise. Method Detailvaluespublic static Rotation[] values() Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (Rotation c : Rotation.values()) System.out.println(c); Returns:an array containing the constants of this enum type, in the order they are declaredvalueOfpublic static Rotation valueOf(String name) Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) Parameters:name - the name of the enum constant to be returned.Returns:the enum constant with the specified nameThrows:IllegalArgumentException - if this enum type has no constant with the specified nameNullPointerException - if the argument is nullSkip navigation linksPackageClassDeprecatedIndexHelpPrev ClassNext ClassFr
  • 32. amesNo FramesAll ClassesSummary: Nested | Enum Constants | Field | MethodDetail: Enum Constants | Field | Method help-doc.html JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll ClassesHow This API Document Is Organized This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows. Package Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain six categories:Interfaces (italic)ClassesEnumsExceptionsErrorsAnnotation Types Class/Interface Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections
  • 33. consisting of a class/interface description, summary tables, and detailed member descriptions:Class inheritance diagramDirect SubclassesAll Known SubinterfacesAll Known Implementing ClassesClass/interface declarationClass/interface descriptionNested Class SummaryField SummaryConstructor SummaryMethod SummaryField DetailConstructor DetailMethod Detail Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer. Annotation Type Each annotation type has its own separate page with the following sections:Annotation Type declarationAnnotation Type descriptionRequired Element SummaryOptional Element SummaryElement Detail Enum Each enum has its own separate page with the following sections:Enum declarationEnum descriptionEnum Constant SummaryEnum Constant Detail Deprecated API The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations. Index The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields. Prev/Next
  • 34. These links take you to the next or previous class, interface, package, or related page. Frames/No Frames These links show and hide the HTML frames. All pages are available with or without frames. All Classes The All Classes link shows all classes and interfaces except non-static nested types. Serialized Form Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description. Constant Field Values The Constant Field Values page lists the static final fields and their values. This help file applies to API documentation generated using the standard doclet. Skip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll Classes index-all.html
  • 35. JavaScript is disabled on your browser. Skip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra mesAll ClassesABEFGHIMNPRSTVW AAI - Interface in edu.vt.cs5044.tetris Interface the game engine uses to communicate with AI implementations. BBoard - Class in edu.vt.cs5044.tetris Represents a Tetris game board, including all fixed blocks. Board() - Constructor for class Board Construct a new empty board with no fixed blocks. Board(String...) - Constructor for class Board Construct a new board with the specified initial blocks. Eedu.vt.cs5044.tetris - package edu.vt.cs5044.tetris This package holds the internal components necessary for the game. equals(Object) - Method in class Board Test for equality with another Board. equals(Object) - Method in class Placement Test for equality with another Placement.
  • 36. FfindBestPlacement(Board, Shape) - Method in interface AI Calculate the best placement available for a shape in a board. GgetColumn() - Method in class Placement Fetch specified column. getColumnHeightVariability(Board) - Method in interface AI Return the variability of column heights of a board (see academic note). getMaximumBlockHeight(Board) - Method in interface AI Compute the maximum block height of a board (see academic note). getResultBoard(Shape, Placement) - Method in class Board Generate a new board that is the result of placing a shape in this board. getRotation() - Method in class Placement Fetch specified rotation. getRotationSet() - Method in enum Shape Get the set of valid rotations for this shape. getTestSet() - Static method in enum RandomMode Fetch the set of all test-related values. getTotalBlockCount(Board) - Method in interface AI Compute the total block count of a board (see academic note). getTotalGapCount(Board) - Method in interface AI
  • 37. Compute the total gap count of a board (see academic note). getWidth(Rotation) - Method in enum Shape Get the width of this shape, in blocks, after applying a specified rotation. HhashCode() - Method in class BoardhashCode() - Method in class PlacementHEIGHT - Static variable in class Board Height of all game boards, in blocks. HEIGHT_LIMIT - Static variable in class Board Height limit of all game boards, in blocks. IisBlockAt(int, int) - Method in class Board Check for a fixed block at a specified location. Mmain(String[]) - Static method in class Tetris5044 For internal use only. NnextShape() - Method in class ShapeStream Fetch the next random Shape from this stream. PPlacement - Class in edu.vt.cs5044.tetris Represents a single possible placement of a shape. Placement(Rotation, int) - Constructor for class Placement
  • 38. Construct a new object with the specified parameters. RRandomMode - Enum in edu.vt.cs5044.tetris Enumerates the modes of randomness used for generating shapes for games of tetris. Rotation - Enum in edu.vt.cs5044.tetris Enumeration representing each of the four distinct rotations in Tetris. SShape - Enum in edu.vt.cs5044.tetris Enumeration representing each of the seven distinct tetromino shapes. ShapeStream - Class in edu.vt.cs5044.tetris Used to generate a stream of random shapes for a game of Tetris. ShapeStream(RandomMode) - Constructor for class ShapeStream Construct a new ShapeStream in the specified RandomMode. start(Stage) - Method in class Tetris5044 For internal use only. TTetris5044 - Class in edu.vt.cs5044.tetris The main application class; for internal use only. Tetris5044() - Constructor for class Tetris5044toString() - Method in class Board
  • 39. Generate a multi-line ASCII art visualization of this board. toString() - Method in class Placement Generates a simple human-readable representation of this object. VvalueOf(String) - Static method in enum RandomMode Returns the enum constant of this type with the specified name. valueOf(String) - Static method in enum Rotation Returns the enum constant of this type with the specified name. valueOf(String) - Static method in enum Shape Returns the enum constant of this type with the specified name. values() - Static method in enum RandomMode Returns an array containing the constants of this enum type, in the order they are declared. values() - Static method in enum Rotation Returns an array containing the constants of this enum type, in the order they are declared. values() - Static method in enum Shape Returns an array containing the constants of this enum type, in the order they are declared. WWIDTH - Static variable in class Board Width of all game boards, in blocks. ABEFGHIMNPRSTVWSkip navigation linksPackageClassDeprecatedIndexHelpPrevNextFramesNo Fra
  • 40. mesAll Classes index.html package-list edu.vt.cs5044.tetris script.js function show(type) { count = 0; for (var key in methods) { var row = document.getElementById(key); if ((methods[key] & type) != 0) { row.style.display = ''; row.className = (count++ % 2) ? rowColor : altColor; } else row.style.display = 'none'; } updateTabs(type); } function updateTabs(type) { for (var value in tabs) { var sNode = document.getElementById(tabs[value][0]); var spanNode = sNode.firstChild; if (value == type) { sNode.className = activeTableTab; spanNode.innerHTML = tabs[value][1]; } else { sNode.className = tableTab; spanNode.innerHTML = "<a href="javascript:show("+
  • 41. value + ");">" + tabs[value][1] + "</a>"; } } } stylesheet.css /* Javadoc style sheet */ /* Overall document style */ @import url('resources/fonts/dejavu.css'); body { background-color:#ffffff; color:#353833; font-family:'DejaVu Sans', Arial, Helvetica, sans-serif; font-size:14px; margin:0; } a:link, a:visited { text-decoration:none; color:#4A6782; } a:hover, a:focus { text-decoration:none; color:#bb7a2a; } a:active { text-decoration:none; color:#4A6782; } a[name] { color:#353833; }
  • 42. a[name]:hover { text-decoration:none; color:#353833; } pre { font-family:'DejaVu Sans Mono', monospace; font-size:14px; } h1 { font-size:20px; } h2 { font-size:18px; } h3 { font-size:16px; font-style:italic; } h4 { font-size:13px; } h5 { font-size:12px; } h6 { font-size:11px; } ul { list-style-type:disc; } code, tt { font-family:'DejaVu Sans Mono', monospace; font-size:14px; padding-top:4px; margin-top:8px; line-height:1.4em;
  • 43. } dt code { font-family:'DejaVu Sans Mono', monospace; font-size:14px; padding-top:4px; } table tr td dt code { font-family:'DejaVu Sans Mono', monospace; font-size:14px; vertical-align:top; padding-top:4px; } sup { font-size:8px; } /* Document title and Copyright styles */ .clear { clear:both; height:0px; overflow:hidden; } .aboutLanguage { float:right; padding:0px 21px; font-size:11px; z-index:200; margin-top:-9px; } .legalCopy { margin-left:.5em; } .bar a, .bar a:link, .bar a:visited, .bar a:active { color:#FFFFFF; text-decoration:none;
  • 44. } .bar a:hover, .bar a:focus { color:#bb7a2a; } .tab { background-color:#0066FF; color:#ffffff; padding:8px; width:5em; font-weight:bold; } /* Navigation bar styles */ .bar { background-color:#4D7A97; color:#FFFFFF; padding:.8em .5em .4em .8em; height:auto;/*height:1.8em;*/ font-size:11px; margin:0; } .topNav { background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; font-size:12px; } .bottomNav { margin-top:10px;
  • 45. background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; font-size:12px; } .subNav { background-color:#dee3e9; float:left; width:100%; overflow:hidden; font-size:12px; } .subNav div { clear:left; float:left; padding:0 0 5px 6px; text-transform:uppercase; } ul.navList, ul.subNavList { float:left; margin:0 25px 0 0; padding:0; } ul.navList li{ list-style:none; float:left; padding: 5px 6px; text-transform:uppercase; } ul.subNavList li{
  • 46. list-style:none; float:left; } .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { color:#FFFFFF; text-decoration:none; text-transform:uppercase; } .topNav a:hover, .bottomNav a:hover { text-decoration:none; color:#bb7a2a; text-transform:uppercase; } .navBarCell1Rev { background-color:#F8981D; color:#253441; margin: auto 5px; } .skipNav { position:absolute; top:auto; left:-9999px; overflow:hidden; } /* Page header and footer styles */ .header, .footer { clear:both; margin:0 20px; padding:5px 0 0 0; } .indexHeader { margin:10px; position:relative;
  • 47. } .indexHeader span{ margin-right:15px; } .indexHeader h1 { font-size:13px; } .title { color:#2c4557; margin:10px 0; } .subTitle { margin:5px 0 0 0; } .header ul { margin:0 0 15px 0; padding:0; } .footer ul { margin:20px 0 5px 0; } .header ul li, .footer ul li { list-style:none; font-size:13px; } /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; }
  • 48. ul.blockList ul.blockList ul.blockList li.blockList h3 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } ul.blockList ul.blockList li.blockList h3 { padding:0; margin:15px 0; } ul.blockList li.blockList h2 { padding:0px 0 20px 0; } /* Page layout container styles */ .contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { clear:both; padding:10px 20px; position:relative; } .indexContainer { margin:10px; position:relative; font-size:12px; } .indexContainer h2 { font-size:13px; padding:0 0 3px 0; } .indexContainer ul { margin:0; padding:0; } .indexContainer ul li {
  • 49. list-style:none; padding-top:2px; } .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { font-size:12px; font-weight:bold; margin:10px 0 0 0; color:#4E4E4E; } .contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { margin:5px 0 10px 0px; font-size:14px; font-family:'DejaVu Sans Mono',monospace; } .serializedFormContainer dl.nameValue dt { margin-left:1px; font-size:1.1em; display:inline; font-weight:bold; } .serializedFormContainer dl.nameValue dd { margin:0 0 0 1px; font-size:1.1em; display:inline; } /* List styles */ ul.horizontal li { display:inline; font-size:0.9em; } ul.inheritance { margin:0;
  • 50. padding:0; } ul.inheritance li { display:inline; list-style:none; } ul.inheritance li ul.inheritance { margin-left:15px; padding-left:15px; padding-top:1px; } ul.blockList, ul.blockListLast { margin:10px 0 10px 0; padding:0; } ul.blockList li.blockList, ul.blockListLast li.blockList { list-style:none; margin-bottom:15px; line-height:1.4; } ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { padding:0px 20px 5px 10px; border:1px solid #ededed; background-color:#f8f8f8; } ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { padding:0 0 5px 8px; background-color:#ffffff; border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { margin-left:0; padding-left:0; padding-bottom:15px;
  • 51. border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { list-style:none; border-bottom:none; padding-bottom:0; } table tr td dl, table tr td dl dt, table tr td dl dd { margin-top:0; margin-bottom:1px; } /* Table styles */ .overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { width:100%; border-left:1px solid #EEE; border-right:1px solid #EEE; border-bottom:1px solid #EEE; } .overviewSummary, .memberSummary { padding:0px; } .overviewSummary caption, .memberSummary caption, .typeSummary caption, .useSummary caption, .constantsSummary caption, .deprecatedSummary caption { position:relative; text-align:left; background-repeat:no-repeat; color:#253441; font-weight:bold; clear:none; overflow:hidden;
  • 52. padding:0px; padding-top:10px; padding-left:1px; margin:0px; white-space:pre; } .overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link, .useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link, .overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover, .useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover, .overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active, .useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active, .overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited, .useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited { color:#FFFFFF; } .overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, .useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; padding-bottom:7px; display:inline-block; float:left; background-color:#F8981D;
  • 53. border: none; height:16px; } .memberSummary caption span.activeTableTab span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; margin-right:3px; display:inline-block; float:left; background-color:#F8981D; height:16px; } .memberSummary caption span.tableTab span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; margin-right:3px; display:inline-block; float:left; background-color:#4D7A97; height:16px; } .memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab { padding-top:0px; padding-left:0px; padding-right:0px; background-image:none; float:none; display:inline; } .overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd,
  • 54. .useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd { display:none; width:5px; position:relative; float:left; background-color:#F8981D; } .memberSummary .activeTableTab .tabEnd { display:none; width:5px; margin-right:3px; position:relative; float:left; background-color:#F8981D; } .memberSummary .tableTab .tabEnd { display:none; width:5px; margin-right:3px; position:relative; background-color:#4D7A97; float:left; } .overviewSummary td, .memberSummary td, .typeSummary td, .useSummary td, .constantsSummary td, .deprecatedSummary td { text-align:left; padding:0px 0px 12px 10px; width:100%; } th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th, td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{
  • 55. vertical-align:top; padding-right:0px; padding-top:8px; padding-bottom:3px; } th.colFirst, th.colLast, th.colOne, .constantsSummary th { background:#dee3e9; text-align:left; padding:8px 3px 3px 7px; } td.colFirst, th.colFirst { white-space:nowrap; font-size:13px; } td.colLast, th.colLast { font-size:13px; } td.colOne, th.colOne { font-size:13px; } .overviewSummary td.colFirst, .overviewSummary th.colFirst, .overviewSummary td.colOne, .overviewSummary th.colOne, .memberSummary td.colFirst, .memberSummary th.colFirst, .memberSummary td.colOne, .memberSummary th.colOne, .typeSummary td.colFirst{ width:25%; vertical-align:top; } td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { font-weight:bold;
  • 56. } .tableSubHeadingColor { background-color:#EEEEFF; } .altColor { background-color:#FFFFFF; } .rowColor { background-color:#EEEEEF; } /* Content styles */ .description pre { margin-top:0; } .deprecatedContent { margin:0; padding:10px 0; } .docSummary { padding:0; } ul.blockList ul.blockList ul.blockList li.blockList h3 { font-style:normal; } div.block { font-size:14px; font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; } td.colLast div { padding-top:0px;
  • 57. } td.colLast a { padding-bottom:3px; } /* Formatting effect styles */ .sourceLineNo { color:green; padding:0 30px 0 0; } h1.hidden { visibility:hidden; overflow:hidden; font-size:10px; } .block { display:block; margin:3px 10px 2px 0px; color:#474747; } .deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink, .overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel, .seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink { font-weight:bold; } .deprecationComment, .emphasizedPhrase, .interfaceName { font-style:italic; } div.block div.block span.deprecationComment, div.block
  • 58. div.block span.emphasizedPhrase, div.block div.block span.interfaceName { font-style:normal; } div.contentContainer ul.blockList li.blockList h2{ padding-bottom:0px; } Commenting guidelines Documenting Your Classes and Methods It is important always to document your code clearly. For Java programmers, some general commenting conventions have been established by a tool called javadoc (Links to an external site.)Links to an external site., the Java API documentation generator. This tool can automatically extract documentation comments from source code and generate HTML class descriptions, like those in the Sofia API (Links to an external site.)Links to an external site.. This tool is so popular and so commonly used that it has set the standard for how people document the externally visible features in their Java code. (See the Sun article on "How to Write Doc Comments for the Javadoc Tool" (Links to an external site.)Links to an external site..) JavaDoc (Links to an external site.)Links to an external site. Comments The javadoc tool expects comments to be written in a particular way--other comments are ignored. JavaDoc comments (also called just "doc comments") always start with "/**" and end with "*/". Any other comments are ignored when generating documentation for your code. Further, a JavaDoc comment describing something always appears immediately before the thing it documents. Within a JavaDoc comment, special tags can be embedded to signal particular kinds of information. These doc tags enable
  • 59. complete, well-formatted API documentation to be automatically generated from your source code. All JavaDoc tags start with an at-sign (@). If you already know some HTML, you can even embed simple HTML markup inside your JavaDoc comments, and it will appear in the generated documentation for your classes. This is handy if you want to add bullet lists in a class description, or wish to make part of your comment stand out in boldface, and so on. Describing a Class You should place a descriptive JavaDoc comment just before the start of each class you write: /** * Write a one-sentence summary of your class here. * Follow it with additional details about its purpose, what abstraction * it represents, and how to use it. * * @author Stephen Edwards (stedwar2) * @version 2011.01.30 */ public class UserProfile . . . { . . . } Class descriptions typically use two tags: @author indicates who wrote the file, and @version indicates the "version" of this file or project. You can use your full name, or just PID, in an @author tag. In this course, it is fine to use the date when the file was written as the version information in the @version tag. When using tags like @author and @version, make sure to put them at the beginning of the line within the doc comment. For the @author line be sure to list your user name (PID) as well as your first and last name. Also, if you started off with a default comment generated by the IDE (like the example above)
  • 60. don't forget to replace the text inside the comment with your own. The javadoc tool will use the very first sentence of your comment as a one-sentence summary of your class, and will use the entire text of your comment as the full class description. Remember that if you just write regular comments, they won't be recognized as "official" descriptive text for document generation: // This comment describes what this class does, but because it // uses //, it won't be recognized as a JavaDoc comment. public class UserProfile . . . { . . . } Documenting a Method You should place a descriptive JavaDoc comment just before each method or constructor you write: /** * Move the robot forward to the next HTML heading. */ public void advanceToNextHeading() { . . . } As with other JavaDoc comments, make sure this appears just before the method it describes. For methods that have parameters, you should also include a brief description of what each parameter means. For example, we might have a UserProfile class that provides a setter method for its name: /** * Set the profile's name to the given value. * * @param newName The new name for this profile. */ public void setName(String newName) {
  • 61. . . . } Here, a @param tag has been used to give a description of the meaning and use of the parameter. Use a separate @param tag to describe each parameter in the method (or constructor). Be sure to start these tags at the beginning of a comment line, and group all of the tags with the same name together (i.e., all @param tags should be next to each other). Again, javadoc will take the first sentence in your comment as a one-sentence summary of what the method does. The remainder of the comment will be used in generating a full description of the method. Some methods have return values--that is, they give back information to their caller. For example, a getName() method might return a String containing the user profile's current name. You can document what information is returned using a @return tag: /** * Get this profile's name. * * @return This profile's name */ public String getName() { . . . } Generating Your Documentation Within an Eclipse project, you can use the Project->Generate Javadoc... command to generate full documentation for your own project straight from your source code. Click Next twice, and in the final screen check to "Open generated index file in browser" near the bottom. Once complete, a new tab will open showing all of the generated documentation for your classes. Other Comments in Your Code JavaDoc comments are "public" documentation of the externally accessible features of your classes. Often, you may also wish to
  • 62. include "internal" (that is, private) documentation that is only useful to someone reading the source code directly. Any comment that does not begin with /** is treated as private, purely for someone with access to the source code. You are free to use such comments where ever you like to improve the readability of your code, but ... Internal Comments Are the Documentation Technique of Last Resort Choose all names carefully so that a naïve reader's first interpretation will always be right. Do not choose names that might mislead someone about what a method is supposed to do, or what information a variable holds. Choosing poor names or convoluted logic structure and then trying to explain it in lengthy comments does little to improve readability. This is doubly true for methods, because half the time a reader will see your method name where it is called, not when they are reading your method itself. If it is not immediately clear what the method should do, that affects the readability of all the code calling this method, no matter how many comments you put in the method itself. Strive to write code that is clear and understandable on its own, simply by virtue of the names you have chosen and the structure you use. If you feel you have to add an internal comment to explain something, ask yourself what needs explaining. If you need to explain what a name refers to or how you intend to use it, consider choosing a better name. If you have to explain a complex series of if statements or some other convoluted structure, ask yourself (or a TA) if there is a better way. Only after considering these alternatives should you add descriptive comments. Redundant Comments Are Worse Than No Comments Consider these comments: user = new UserProfile(); // Create a new user profile x = x + 1; // Add one to x
  • 63. user.setName("Ben"); // change the profile name These are examples of useless comments. Many students add comments to their code just to "make sure everything is documented," or because they believe copious comments are what the instructor is looking for. Comments like this just get in the way of reading the code, however. You should only add comments when they express something that isn't already evident from the code itself. Comments are more information that the poor reader has to wade through, so you need to carefully balance their benefits against the cost of having to read them. This reader might be - and often will be - you, so a good mental model to adopt is that you are writing comments as messages to your future self. This future you will be more experienced than the current you when it comes to programming, but will have forgotten the details of the code written even a week ago. You should write your comments with an eye towards minimizing the mental effort this future you has to expend to be able to understand and maintain your code. META-INF/MANIFEST.MF Manifest-Version: 1.0 Implementation-Title: Tetris 5044 Permissions: sandbox Codebase: * JavaFX-Version: 8.0 Class-Path: Created-By: JavaFX Packager
  • 64. Implementation-Vendor: Main-Class: edu.vt.cs5044.tetris.Tetris5044 edu/vt/cs5044/tetris/AI.classpackage edu.vt.cs5044.tetris; publicabstractinterface AI { publicabstract Placement findBestPlacement(Board, Shape); publicabstract int getMaximumBlockHeight(Board); publicabstract int getTotalBlockCount(Board); publicabstract int getTotalGapCount(Board); publicabstract int getColumnHeightVariability(Board); } edu/vt/cs5044/tetris/Board.classpackage edu.vt.cs5044.tetris; publicsynchronizedclass Board { publicstaticfinal int WIDTH = 10; publicstaticfinal int HEIGHT = 24; publicstaticfinal int HEIGHT_LIMIT = 20; privatefinal java.util.Set blockSet; public void Board(); Board getCopy(); publictransient void Board(String[]); private boolean isCollision(Piece, Coordinate); public boolean isBlockAt(int, int); public Board getResultBoard(Shape, Placement); void clear(); boolean isValidMove(Placement, Piece); java.util.Set getBlockSet(); void addBlocks(java.util.Set); private boolean isRowFilled(int); private void shiftRowsDownTo(int);
  • 65. int clearRows(); public String toString(); public boolean equals(Object); public int hashCode(); } edu/vt/cs5044/tetris/Box$1.classpackage edu.vt.cs5044.tetris; synchronizedclass Box$1 extends javafx.beans.binding.ObjectBinding { void Box$1(Box); protected Number computeValue(); } edu/vt/cs5044/tetris/Box$2.classpackage edu.vt.cs5044.tetris; synchronizedclass Box$2 extends javafx.beans.binding.ObjectBinding { void Box$2(Box); protected Number computeValue(); } edu/vt/cs5044/tetris/Box$3.classpackage edu.vt.cs5044.tetris; synchronizedclass Box$3 extends javafx.beans.binding.ObjectBinding { void Box$3(Box); protected Number computeValue(); } edu/vt/cs5044/tetris/Box.classpackage edu.vt.cs5044.tetris; synchronizedclass Box extends javafx.scene.shape.Rectangle { privatefinal Coordinate coord; privatefinal GameManager manager; void Box(GameManager, Coordinate);
  • 66. Coordinate getCoordinate(); } edu/vt/cs5044/tetris/Coordinate.classpackage edu.vt.cs5044.tetris; finalsynchronizedclass Coordinate { privatefinal int x; privatefinal int y; static Coordinate at(int, int); private void Coordinate(int, int); int getX(); int getY(); Coordinate shiftLeft(); Coordinate shiftRight(); Coordinate shiftUp(); Coordinate shiftDown(); Coordinate relativeTo(Coordinate); public String toString(); public boolean equals(Object); public int hashCode(); } edu/vt/cs5044/tetris/GameManager$1.classpackage edu.vt.cs5044.tetris; synchronizedclass GameManager$1 { static void <clinit>(); } edu/vt/cs5044/tetris/GameManager.classpackage edu.vt.cs5044.tetris; synchronizedclass GameManager { privatefinal javafx.scene.layout.Pane gamePane; privatefinal javafx.scene.layout.Pane innerPane;
  • 67. privatefinal Board board; privatefinal java.util.Map boxMap; privatefinal InfoPane infoPane; privatefinal ScorePane scorePane; privatefinal javafx.animation.Timeline dropTimeline; private boolean readyToPlay; private UserPlacement placement; private AI brain; private boolean brainActive; privatefinal javafx.beans.property.SimpleIntegerProperty pcountProp; privatefinal javafx.beans.property.SimpleIntegerProperty rclearProp; private int speedLevel; private boolean turboMode; private RandomMode randomMode; private ShapeStream shapeStream; void GameManager(javafx.scene.layout.Pane, Board); final void gameOver(); javafx.scene.layout.Pane getParentPane(); void addBlocks(java.util.Set); final void placeNextPiece(); void start(); javafx.beans.property.SimpleIntegerProperty getPcountProp(); javafx.beans.property.SimpleIntegerProperty getRclearProp(); private void startDropTimer(); } edu/vt/cs5044/tetris/InfoPane$1.classpackage edu.vt.cs5044.tetris; synchronizedclass InfoPane$1 extends javafx.beans.binding.DoubleBinding { void InfoPane$1(InfoPane, javafx.scene.text.Text);
  • 68. protected double computeValue(); } edu/vt/cs5044/tetris/InfoPane.classpackage edu.vt.cs5044.tetris; synchronizedclass InfoPane extends javafx.scene.layout.StackPane { void InfoPane(); void setup(GameManager); void show(); void hide(); } edu/vt/cs5044/tetris/Piece.classpackage edu.vt.cs5044.tetris; synchronizedclass Piece { privatefinal Shape shape; privatefinal Rotation rotation; privatefinal int minX; privatefinal int maxX; privatefinal int minY; privatefinal int maxY; privatefinal java.util.Set blockSet; void Piece(Shape, Rotation); Piece nextRotation(); Shape getShape(); Rotation getRotation(); java.util.Set getBlocks(); int getWidth(); int getMaxX(); int getMinX(); int getMaxY(); int getMinY(); public boolean equals(Object); public int hashCode(); public String toString();
  • 69. } edu/vt/cs5044/tetris/Placement.classpackage edu.vt.cs5044.tetris; publicsynchronizedclass Placement { privatefinal Rotation rotation; privatefinal int column; public void Placement(Rotation, int); public Rotation getRotation(); public int getColumn(); public String toString(); public boolean equals(Object); public int hashCode(); } edu/vt/cs5044/tetris/RandomMode$1.classpackage edu.vt.cs5044.tetris; synchronizedclass RandomMode$1 { static void <clinit>(); } edu/vt/cs5044/tetris/RandomMode.classpackage edu.vt.cs5044.tetris; publicfinalsynchronizedenum RandomMode { publicstaticfinal RandomMode NORMAL; publicstaticfinal RandomMode TEST1; publicstaticfinal RandomMode TEST2; publicstaticfinal RandomMode TEST3; publicstaticfinal RandomMode TEST4; privatefinal int value; publicstatic RandomMode[] values(); publicstatic RandomMode valueOf(String); private void RandomMode(String, int, int);
  • 70. RandomMode next(); int getValue(); publicstatic java.util.Set getTestSet(); static void <clinit>(); } edu/vt/cs5044/tetris/Rotation$1.classpackage edu.vt.cs5044.tetris; synchronizedclass Rotation$1 { static void <clinit>(); } edu/vt/cs5044/tetris/Rotation.classpackage edu.vt.cs5044.tetris; publicfinalsynchronizedenum Rotation { publicstaticfinal Rotation NONE; publicstaticfinal Rotation CCW_90; publicstaticfinal Rotation CCW_180; publicstaticfinal Rotation CCW_270; privatefinal int value; publicstatic Rotation[] values(); publicstatic Rotation valueOf(String); private void Rotation(String, int, int); int getValue(); Rotation getNext(); static void <clinit>(); } edu/vt/cs5044/tetris/ScorePane$1.classpackage edu.vt.cs5044.tetris; synchronizedclass ScorePane$1 extends javafx.beans.binding.ObjectBinding { void ScorePane$1(ScorePane, GameManager); protected String computeValue();
  • 71. } edu/vt/cs5044/tetris/ScorePane$2.classpackage edu.vt.cs5044.tetris; synchronizedclass ScorePane$2 extends javafx.beans.binding.DoubleBinding { void ScorePane$2(ScorePane, javafx.scene.text.Text); protected double computeValue(); } edu/vt/cs5044/tetris/ScorePane.classpackage edu.vt.cs5044.tetris; synchronizedclass ScorePane extends javafx.scene.layout.StackPane { void ScorePane(); void setup(GameManager); void show(); void hide(); } edu/vt/cs5044/tetris/Shape.classpackage edu.vt.cs5044.tetris; publicfinalsynchronizedenum Shape { publicstaticfinal Shape I; publicstaticfinal Shape O; publicstaticfinal Shape T; publicstaticfinal Shape J; publicstaticfinal Shape L; publicstaticfinal Shape S; publicstaticfinal Shape Z; privatefinal java.util.List coordSetList; privatefinal java.util.Set rotationSet; publicstatic Shape[] values(); publicstatic Shape valueOf(String);
  • 72. privatetransient void Shape(String, int, java.util.List[]); public java.util.Set getRotationSet(); public int getWidth(Rotation); int countOrientations(); java.util.Set getBlocks(int); static void <clinit>(); } edu/vt/cs5044/tetris/ShapeStream.classpackage edu.vt.cs5044.tetris; publicsynchronizedclass ShapeStream { privatefinal java.util.Random random; public void ShapeStream(RandomMode); public Shape nextShape(); } edu/vt/cs5044/tetris/Tetris5044.classpackage edu.vt.cs5044.tetris; publicsynchronizedclass Tetris5044 extends javafx.application.Application { public void Tetris5044(); public void start(javafx.stage.Stage) throws Exception; publicstatic void main(String[]); } edu/vt/cs5044/tetris/Tetris5044Launcher$1.classpackage edu.vt.cs5044.tetris; finalsynchronizedclass Tetris5044Launcher$1 extends javafx.beans.binding.ObjectBinding { void Tetris5044Launcher$1(javafx.stage.Stage); protected javafx.geometry.Insets computeValue(); }
  • 73. edu/vt/cs5044/tetris/Tetris5044Launcher.classpackage edu.vt.cs5044.tetris; synchronizedclass Tetris5044Launcher { void Tetris5044Launcher(); static void launch(javafx.stage.Stage); } edu/vt/cs5044/tetris/UserPlacement.classpackage edu.vt.cs5044.tetris; finalsynchronizedclass UserPlacement extends javafx.scene.Group { privatefinal GameManager manager; privatefinal Board board; privatefinal java.util.Set boxSet; private Piece piece; private Coordinate coord; void UserPlacement(GameManager, Board, Piece, Coordinate); Piece getPiece(); private boolean isBoardCollision(Piece, Coordinate); void lockIntoBoard(); void rotate(); void applyMove(Placement); void toColumn(int); void shiftLeft(); void shiftRight(); boolean shiftDown(); void forceUp(); final void createBoxes(); } edu/vt/cs5044/tetris/package-info.classpackage edu.vt.cs5044.tetris;
  • 74. interface package-info { } Project 3 - Play Tetris Overview Tetris (Links to an external site.)Links to an external site. was arguably the most popular single-player computer game of all time by the early 1990's. It's incredibly simple and fun to play, and even to this day it's widely considered to be among the best games of all time. In case you've never seen it, the game consists of a 10-unit wide by 24-unit tall well, into which randomly-selected geometric 4- unit pieces begin to fall one at a time. The player manipulates each piece as it falls, by moving it horizontally within the well, and rotating it in 90° increments. Once the piece can fall no further, it becomes locked in place, taking up space in the well. However, if the player forms one or more full horizontal (10- unit by 1-unit) rows, those rows are removed, with all rows above shifting downward. The goal is to continue playing as long as possible, so the player must attempt to pack the pieces strategically. Eventually, though, the well fills upward to a limit line, and if any portion of a piece is locked in place above this line, the game is over. You'll see all of this in action soon enough, and it's actually quite easy to understand once you've played it for just a few minutes. Requirements Building a full-functional Tetris application requires a little more Java than what we've covered yet this term, so you'll be provided a working application that you can download and play. It's a somewhat simplified version, with a very rudimentary scoring mechanism, but it's still just as enjoyable and challenging as the original. So, if the application is already provided, what is this assignment all about? The goal here is to develop a basic
  • 75. Artificial Intelligence ("AI") system, capable of controlling the game as if it were the player. Implementing an Interface In previous assignments, you were given a class file with method declarations, Javadoc comments, and placeholder implementations. In this assignment, you'll be given an interface instead. An interface contains the method declarations and the Javadoc comments, but no code at all (not even placeholders). Your task is to implement this interface, which means you'll develop a class that provides code for all the methods declared in the interface. In addition to the methods specified by the interface, you will likely need to develop several private helper methods in order to fully implement it without redundancies. System Description The interface you will implement is called edu.vt.cs5044.tetris.AI and your implementation class must be called edu.vt.cs5044.TetrisAI. You will need to develop the code needed to implement the methods defined by the interface. One of the methods will be the overall AI system. This method receives some parameters, defining the current state of the game board and the shape to be placed, and will need to find the "best" placement for that shape. The other methods are responsible for intermediate calculations. These methods would normally be private, and not specified by the interface, but for academic purposes we're exposing these methods to ease the testing requirements. Speaking of tests, your JUnit test file must be called edu.vt.cs5044.TetrisAITest. Downloads tetris5044.jar library file containing all the compiled game engine classes tetris5044-api.jar library file containing the Javadocs for the game engine Setting up Eclipse
  • 76. Download the provided files to your computer, and place them in a convenient folder. Open Eclipse and create a new Java Project for this assignment. Right-click the project and select Build Path | Configure Build Path, then select the Libraries tab. Click Add External JARs and navigate to where you placed the downloaded JAR files, select tetris5044.jar, and click OK. You should now see that file listed just above the JRE System Library. Now click the little triangle to expand the new file, select Javadoc location: (None), and click the "Edit..." button. Here be sure to select "Javadoc in archive" first, then click Browse. Navigate again, this time selecting tetris5044-api.jar, and click Validate. It should tell you the location is likely valid, so click OK, then OK, then OK to get back to your project. Your should see a new Referenced Libraries section, which you can expand to see the tetris5044.jar file. Shall We Play a Game? (better than tic-tac-toe) At this point, you can right-click your project and select Run As | Java Application to play Tetris! Go ahead and try it now... A window should appear with an empty game board and a prompt to type P to play. Once you type P, you will see a new random piece near the top, slowly falling toward the bottom of the well. There are several alternative keyboard controls you can use, but for now just type J and L to move the piece left and right, and type I to rotate the piece. Once the piece is situated as you wish, you can use K or the space bar to drop the piece immediately, or you can just enjoy watching the piece fall gently into place. Zombie (brains?) You can type '?' into the game at any time to produce a listing in the Eclipse console of all of the available options and keyboard controls. Some of these options will be extremely useful during the assignment. Try that now. You'll probably notice some interesting options, including a way to enable the Player AI by typing Ctrl-P. When you enable this mode, just before a new shape appears in the game, the AI is asked how to
  • 77. best rotate then position the shape. Go ahead and attempt that now. Nothing will happen, except you'll see a warning in the console that your implementation couldn't be found, which is perfectly understandable at this point. Trying to Take Over the World (no, not that Brain) Close the game for a moment now, while we get some of the basics for the code in place. First, create a new package in your src folder called edu.vt.cs5044 then right-click within that package select New Class. Before you enter the class name, click the "Add..." button to the right of the Interfaces section. In the search box at the top, type AI and you should soon see the AI interface (in the edu.vt.cs5044.tetris package) selected. Click Ok to add that interface, and now you can enter the class name TetrisAI and click Finish. Notice that the new file declaration says public class TetrisAI implements AI. This is what tells Java that we intend to be compatible with any system that can work with the AI interface. You'll also notice Eclipse is already showing an error on the class declaration line. Click the tiny red X in the margin and double-click "Add unimplemented methods" from the pop- up. This asks Eclipse to generate all the method placeholders for you! Save the file, and check out your implementation. It's already compatible with the game system, even though all it does is return placeholders. That's not very useful, of course, but it's actually enough to get started. Let's see if it's recognized by the game engine. Launch the application again, type Ctrl-P to activate the Player AI, and confirm that the console says the Player AI is now on. If so, go ahead and type P to start the game. Well, that's not very exciting. The console just keeps saying that the AI selected an invalid move for each shape, and we still have to manually place the pieces. That's fair enough, since all we have are placeholders that Eclipse generated for us, but at least we know the game found our AI and seems to be communicating with it. Close the game again now so we can code a little more.
  • 78. Let's at least provide a valid suggestion, even if it's always exactly the same suggestion. In the findBestPlacement() method, let's replace the placeholder: return null; with this: return new Placement(Rotation.NONE, 0); Eclipse will complain that it doesn't know about the Rotation class yet, so again click the tiny X in the margin and double- click to import the Rotation class from the edu.vt.cs5044 package. That should resolve the error, so save your file again. This really doesn't seem like much of an improvement, but we'll try it anyway. Launch the game and use Ctrl-P then P to check it out. So, now it's just placing everything against the left edge (column 0) without any rotation, which is still fairly lame, but it's clear that our AI is actually placing the pieces automatically for us! Things can only get better from here. Close the game once you're ready to code again. Need More Input (accidental AI, maybe) Obviously we need to examine the shape and the state of the board in order to make some reasonable decisions. Let's take a look at all those Javadocs that make up the API. In your source file click within the word AI of "implements AI" and type Shift- F2. This should open the Javadocs for the AI interface using an internal browser within Eclipse. You can set it to use an external browser, if you prefer, but this is fine for now. Reading the Javadocs, click the findBestPlacement() method and you'll see it actually provides a brief outline of a strategy. We apparently need to iterate over each possible rotation, and for each rotation we need to iterate over every possible column placement. For each of these, we need ask the Board object to tell us what the result of any hypothetical move would be. Click the method Board.getResultBoard() to see how that works. The Javadocs say that the original board instance is not modified, and we'll get a new board instance that we can
  • 79. examine. That will meet our needs, but how do we examine one of these hypothetical results? There are only a few other methods available in the Board class. One provides a human-readable rendering of the board, which might prove very useful to visualize what's happening while debugging, and another promising method seems to let us query any location within the board to see which locations are occupied by fixed blocks. There are also some static constants that tell us the overall size of the board, plus two constructors. One of the constructors allows us to generate arbitrary board configurations, which is exactly what we'll need in order to create some nice test cases. Click the Package link at the very top of any Javadoc page to see the package overview, then navigate throughout the various pages to see what each class and enum can do, along with the requirements for the interface. A fundamental part of this assignment is to learn how to use Javadocs to explore unknown libraries, as well as to see how a somewhat larger scale system is divided into multiple classes, each with its own purpose. Note that class Tetris5044 is for internal use only; you won't need it at all. Also, classes RandomMode and ShapeStream are only needed for the optional "challenge" section below. Strategy Games There's no such thing as a perfect Tetris strategy, so we won't even try. We are necessarily taking the heuristic (Links to an external site.)Links to an external site. approach to this problem, and there will necessarily be trade-offs involved. In every placement decision, there are advantages and disadvantages. How can we hope to find the "best" placement? Now is probably a good time to look at those other methods in the interface. Costs and Benefits From the API, it seems the remaining methods of the interface are related to making some measurements to evaluate a board position. The idea here is that we'll compute four distinct
  • 80. "cost" scores, or factors, which tell our system something about how bad (or good) a particular placement might be. We'll need to develop those method first, before we can hope to have a working AI system. We're still focusing on TDD, so start with some fairly straightforward test cases to ensure the individual scoring methods work. Just construct a test board object, then assert the cost score you expect your implementation to compute. Once all of your individual cost scoring methods are working properly as expected, its time to put it all together. The findBestPlacement() method will need to iterate through all the possible placements, and for each it will combine these individual cost scores in a weighted sum, then choose the lowest cost to return to the game engine. The weightings are important so that certain factors can have more influence on the overall decision than others. At first you can just set all the weights to 1, by simply summing the individual scores together, even though eventually we'll need to adjust the weights to achieve better results. Strategic Default Luck plays a starring role in Tetris. Even with the best of strategies, it's critical to recognize that some games simply provide a more fortunate sequence of shapes than others. Thus it can be difficult to objectively judge exactly how good a particular strategy might be. To help with this, our implementation provides a set of 4 repeatable test sequences we can use as a benchmark. The average number of pieces placed from these 4 test sequences will act as a very reasonable metric of how well our strategy is working overall. Teaching to the Test Eventually we'll be making a linear combination of our four scores, which just means we multiply each score by some weight, then add the weighted scores. The equation is very straightforward: overallCost = weight1*score1 + weight2*score2 + weight3*score3 + weight4*score4
  • 81. Computing the individual scores really isn't too bad, but what about the weights? As noted above, we can start by simply setting all the weights to 1, and indeed that strategy will place an average of just above 100 pieces for each of the provided test sequences. Standards of Learning Can we do better? Sure! As a start, reasonable weight ranges for the selected factors will be 0 through 15. You can just use trial-and-error if you wish; watch your AI play the test games and try to figure out which factors need more or less emphasis. For example, if your AI is creating too many unnecessary gaps, try to increase the weight of the gap count score. Be sure to use Turbo mode and all the Random TEST modes. Your AI must be able to place at least 200 pieces, on average, across the provided test sequences. Try adjusting your weights in increments of 5, meaning weight values of 0, 5, 10, and 15. Of the 256 possible combinations of 0, 5, 10, and 15 as weights, about 10% will result in this level of performance. You don't need to provide a JUnit test to demonstrate this performance, but Web-CAT will check whether your system meets this minimum or not. More than Full Coverage Unlike in the previous assignment, creating JUnit tests to cover all of your code will be very straightforward, since there aren't very many branches involved in the solution. You can likely achieve full coverage with just one well-designed test case that asserts something about each method. As a result, complete coverage is not nearly enough to ensure you have correctly implemented your code. Therefore, you must generate at least 5 test cases for each interface method, with non-trivial tests and non-trivial assertions. You can satisfy this by creating at least 5 distinct test boards to be shared among assertions involving all methods. Just be sure the test boards cover a reasonably wide range of scenarios. Note that Web-CAT won't (and can't) enforce this requirement, but the human grader will definitely be looking for this.
  • 82. Functional Decomposition Judicious use of helper methods can significantly reduce the overall amount of code you need to develop. For example, you might want to create a helper method that returns the height of one specified column. You can then call that method from within a loop of all columns, and use the return value to help compute some of the cost factors your. Your code will be inspected during the human review for redundancies, so be sure to develop helper methods wherever appropriate. Automating the Automation You might have noticed that it can get somewhat tedious to try every combination of 0, 5, 10, and 15 for each of the weights, even in Turbo mode. You might have also noticed that you've been given sufficient tools to run entire simulated games without the user interface at all. As a challenge, see if you can identify the very best combination of 0, 5, 10, and 15 weights, by writing a separate class file called edu.vt.cs5044.WeightFinder with its own main() method. This file will be completely ignored by Web- CAT, and you don't need to generate any tests for it at all. You'll also need to add a public method, such as setWeights(int w1, int w2, int w3, int w4) to your TetrisAI implementation, to apply the various weight combinations. This method will need to be exercised by a single assert, just to be sure it's covered within your own JUnit tests. Once you've found the optimum combination, you'll need to hard-code those values back into your AI as the defaults, in order to watch them in action. The best weights among these combinations will place an average of over 480 pieces for the test sequences. That's quite an improvement, unless you happened to get very lucky in your trial and error phase! Confirm that this is all working as expected, and that you're placing 480+ pieces on average for the test sequences before the next part of the challenge. It should be a simple change to your code to try stepping by 3 instead of 5 (meaning you should test every combination of 0, 3, 6, 9, 12, and 15 for every weight).
  • 83. This process takes about 5-10 times longer to run than stepping by 5. However, if everything was already working properly, you'll only need to do this once, and you'll discover that your newly-tuned weights will average over 1,900 pieces placed for the test sequences. We'll call that a definite win! Still not satisfied? You can always try stepping by 1 instead. Again it's a trivial code change, but note that this process takes about 50-100 times longer to run than stepping by 3, so we're likely talking about a few hours at this point. However, your newly-optimized AI possess the astonishing capability of averaging over 6,100 pieces placed for the test sequences! You might be somewhat amazed when you discover the optimum weightings. Also, you're in for a bit of a surprise when you watch this in action, specifically comparing the results of the TEST1 sequence to those of the TEST2 sequence. If you make any progress with this OPTIONAL challenge, please add a brief write-up in the comments of your WeightFinder class, just to let us know what you did, along with any thoughts you'd like to share about the experience. Of course you may also discuss this in Piazza, although please don't post your code (or any weightings you find) to the entire class, so as not to spoil the fun for anyone else. Hopefully you enjoyed this challenge! Submit to Web-CAT Submit your solution to Web-CAT (Links to an external site.)Links to an external site. via Eclipse or the web interface. Please feel free to improve and resubmit your code as many times as you like (before the deadline) in order to improve your score. Important Notes: · Your submission will be evaluated both by Web-CAT (40 points) and by human (40 points). As such, Web-CAT's automated score will show at most 40/80 points. · Your JUnit test class will be evaluated by Web-CAT to ensure complete coverage of you implementation code, but it will NOT be evaluated for style. Web-CAT will also use its own internal
  • 84. test suite (that we've developed) to evaluate your system. · Carefully review your feedback. In the summary, you will see a table listing each of your source files with a green/red bar by each non-test file. If the bar for any file is not completely green, then some code in that file was not exercised by your own tests. Click the file name to view your source code and look for lines that are highlighted in a pink color. Hover your mouse over highlighted lines for additional information. You will need to add at least one test case to exercise the highlighted code. This includes testing the same actions you've already tested, but starting from different initial conditions. · See the program grading rubric for full details on the grading criteria applied to this assignment. CS 5044 Object-Oriented Programming with Java Q&A Session Midterm Exam • Exam is split into three parts, all due Monday (7/3) at noon ET – Each part has a 30 minute time limit for 20 multiple-choice questions – Each part covers a cross-section of all materials from Module 1 through Module 5 – See also Piazza @166 (and posts linked from there) for a few more details
  • 85. Project 3 - Play Tetris • Tetris! – We've been tasked to develop an artificial intelligence (AI) that can play Tetris • An "interface" has been provided; you will implement the interface – We'll learn more about interfaces in several weeks, but for now: • An interface is just a way in Java to specify required methods, without any code • To implement the interface, we develop a class with actual code in these methods – Eclipse can generate the placeholder methods for us automatically • Once that's done, it becomes just like our previous projects • Plus, the compiler will ensure we don't accidentally change the method headers Meet the Cast of Players • enum Shape – One value for each of the seven geometric pieces involved: – Each Shape provides a set of distinct Rotation values (default orientations shown above) – You can also request the width of the shape (in blocks) after applying any valid Rotation • enum Rotation – One value for each 90° rotation:
  • 86. • NONE • CCW_90 • CCW_180 • CCW_270 Game On • class Placement – A Placement just holds a Rotation value and a column number together – This is what our AI needs to return to the game engine, for any Shape: • First the Rotation will be applied to the Shape • Then the rotated Shape will be moved horizontally – The left-most block will be placed in the specified column – Invalid Placement objects will be rejected (and ignored) by the game engine • class Board – Represents the state of the playing board at any given time – Provides static int values: WIDTH, HEIGHT, and HEIGHT_LIMIT – Contains a collection of fixed blocks; allows us to query via isBlockAt(col, row) – We can ask the board to show us the hypothetical result of placing another piece • The piece will be placed and dropped, then any full rows will be cleared • Creates a new Board object; does not mutate the existing Board
  • 87. – We can also construct new Board objects with arbitrary blocks for testing • ShapeStream and RandomMode are only used for the optional challenge • Tetris5044 is for internal use only, by the game engine itself Mind Games • interface AI – This is what we need to implement! – public Placement findBestPlacement(Board currentBoard, Shape shape) • This is how the game engine asks our AI what to do – The remaining methods need to compute "cost" factors for a given board: • int getColumnHeightVariability(Board board) • int getMaximumBlockHeight(Board board) • int getTotalBlockCount(Board board) • int getTotalGapCount(Board board) • Academic Note: Normally these would be private, and not required by the interface – The individual cost factor methods should be developed (and tested!) first – Once you've completed at least one cost factor method, to find the best placement: • For every possible placement of this shape – Get the board that would result from this placement – Calculate cost factors for result board and combine with weights – If this is the lowest overall cost so far, consider this
  • 88. placement as the new best • Return the best placement to the game engine – Adjust the weights to meet minimum average performance requirements in TEST modes