diff --git a/.metadata/.plugins/org.eclipse.wb.discovery.core/Thumbs.db b/.metadata/.plugins/org.eclipse.wb.discovery.core/Thumbs.db new file mode 100644 index 0000000..4f76ef8 Binary files /dev/null and b/.metadata/.plugins/org.eclipse.wb.discovery.core/Thumbs.db differ diff --git a/MathGames Website/Thumbs.db b/MathGames Website/Thumbs.db new file mode 100644 index 0000000..d845c39 Binary files /dev/null and b/MathGames Website/Thumbs.db differ diff --git a/MathGames Website/images/Thumbs.db b/MathGames Website/images/Thumbs.db index 4059ee9..23f0d29 100644 Binary files a/MathGames Website/images/Thumbs.db and b/MathGames Website/images/Thumbs.db differ diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..185e4b8 --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project MathGame. + + + diff --git a/build/built-jar.properties b/build/built-jar.properties new file mode 100644 index 0000000..19079b1 --- /dev/null +++ b/build/built-jar.properties @@ -0,0 +1,4 @@ +#Thu, 10 Mar 2016 13:28:45 -0500 + + +C\:\\Users\\Zarir\ Hamza\\Documents\\NetBeansProjects\\Math-Game-develop\ -\ Copy= diff --git a/build/classes/.netbeans_automatic_build b/build/classes/.netbeans_automatic_build new file mode 100644 index 0000000..e69de29 diff --git a/build/classes/.netbeans_update_resources b/build/classes/.netbeans_update_resources new file mode 100644 index 0000000..e69de29 diff --git a/build/classes/MathGames UML 1.ucls b/build/classes/MathGames UML 1.ucls new file mode 100644 index 0000000..5d1e302 --- /dev/null +++ b/build/classes/MathGames UML 1.ucls @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/build/classes/audio/button.wav b/build/classes/audio/button.wav new file mode 100644 index 0000000..cf637f1 Binary files /dev/null and b/build/classes/audio/button.wav differ diff --git a/build/classes/audio/incorrect.wav b/build/classes/audio/incorrect.wav new file mode 100644 index 0000000..64a2869 Binary files /dev/null and b/build/classes/audio/incorrect.wav differ diff --git a/build/classes/audio/lose.wav b/build/classes/audio/lose.wav new file mode 100644 index 0000000..a1bdb17 Binary files /dev/null and b/build/classes/audio/lose.wav differ diff --git a/build/classes/audio/merge.wav b/build/classes/audio/merge.wav new file mode 100644 index 0000000..03dc240 Binary files /dev/null and b/build/classes/audio/merge.wav differ diff --git a/build/classes/audio/success.wav b/build/classes/audio/success.wav new file mode 100644 index 0000000..50547d2 Binary files /dev/null and b/build/classes/audio/success.wav differ diff --git a/build/classes/audio/wait.wav b/build/classes/audio/wait.wav new file mode 100644 index 0000000..49872c0 Binary files /dev/null and b/build/classes/audio/wait.wav differ diff --git a/build/classes/audio/win.wav b/build/classes/audio/win.wav new file mode 100644 index 0000000..e6fbb4e Binary files /dev/null and b/build/classes/audio/win.wav differ diff --git a/build/classes/com/mathgame/cardmanager/Move.class b/build/classes/com/mathgame/cardmanager/Move.class new file mode 100644 index 0000000..b9dda20 Binary files /dev/null and b/build/classes/com/mathgame/cardmanager/Move.class differ diff --git a/build/classes/com/mathgame/cardmanager/MoveTracker.class b/build/classes/com/mathgame/cardmanager/MoveTracker.class new file mode 100644 index 0000000..1e6a8f4 Binary files /dev/null and b/build/classes/com/mathgame/cardmanager/MoveTracker.class differ diff --git a/build/classes/com/mathgame/cardmanager/UndoButton.class b/build/classes/com/mathgame/cardmanager/UndoButton.class new file mode 100644 index 0000000..5e64b43 Binary files /dev/null and b/build/classes/com/mathgame/cardmanager/UndoButton.class differ diff --git a/build/classes/com/mathgame/cards/ImageGenerator.class b/build/classes/com/mathgame/cards/ImageGenerator.class new file mode 100644 index 0000000..70fe45c Binary files /dev/null and b/build/classes/com/mathgame/cards/ImageGenerator.class differ diff --git a/build/classes/com/mathgame/cards/NumberCard.class b/build/classes/com/mathgame/cards/NumberCard.class new file mode 100644 index 0000000..08247fe Binary files /dev/null and b/build/classes/com/mathgame/cards/NumberCard.class differ diff --git a/build/classes/com/mathgame/cards/OperationCard.class b/build/classes/com/mathgame/cards/OperationCard.class new file mode 100644 index 0000000..320bb0f Binary files /dev/null and b/build/classes/com/mathgame/cards/OperationCard.class differ diff --git a/build/classes/com/mathgame/cards/ValidationBox$1.class b/build/classes/com/mathgame/cards/ValidationBox$1.class new file mode 100644 index 0000000..d45d0db Binary files /dev/null and b/build/classes/com/mathgame/cards/ValidationBox$1.class differ diff --git a/build/classes/com/mathgame/cards/ValidationBox.class b/build/classes/com/mathgame/cards/ValidationBox.class new file mode 100644 index 0000000..1d12a30 Binary files /dev/null and b/build/classes/com/mathgame/cards/ValidationBox.class differ diff --git a/build/classes/com/mathgame/database/GameAccess.class b/build/classes/com/mathgame/database/GameAccess.class new file mode 100644 index 0000000..4c0ae40 Binary files /dev/null and b/build/classes/com/mathgame/database/GameAccess.class differ diff --git a/build/classes/com/mathgame/database/MatchesAccess.class b/build/classes/com/mathgame/database/MatchesAccess.class new file mode 100644 index 0000000..9b80365 Binary files /dev/null and b/build/classes/com/mathgame/database/MatchesAccess.class differ diff --git a/build/classes/com/mathgame/database/MySQLAccess.class b/build/classes/com/mathgame/database/MySQLAccess.class new file mode 100644 index 0000000..582b516 Binary files /dev/null and b/build/classes/com/mathgame/database/MySQLAccess.class differ diff --git a/build/classes/com/mathgame/database/SQLProject.class b/build/classes/com/mathgame/database/SQLProject.class new file mode 100644 index 0000000..26923be Binary files /dev/null and b/build/classes/com/mathgame/database/SQLProject.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameButton.class b/build/classes/com/mathgame/guicomponents/GameButton.class new file mode 100644 index 0000000..5f6a781 Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameButton.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameDialogFactory$1.class b/build/classes/com/mathgame/guicomponents/GameDialogFactory$1.class new file mode 100644 index 0000000..0e9adc6 Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameDialogFactory$1.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameDialogFactory$2.class b/build/classes/com/mathgame/guicomponents/GameDialogFactory$2.class new file mode 100644 index 0000000..676e115 Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameDialogFactory$2.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameDialogFactory$3.class b/build/classes/com/mathgame/guicomponents/GameDialogFactory$3.class new file mode 100644 index 0000000..ac619ab Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameDialogFactory$3.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameDialogFactory$4.class b/build/classes/com/mathgame/guicomponents/GameDialogFactory$4.class new file mode 100644 index 0000000..aeeff5e Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameDialogFactory$4.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameDialogFactory$GameDialog.class b/build/classes/com/mathgame/guicomponents/GameDialogFactory$GameDialog.class new file mode 100644 index 0000000..83ef6c4 Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameDialogFactory$GameDialog.class differ diff --git a/build/classes/com/mathgame/guicomponents/GameDialogFactory.class b/build/classes/com/mathgame/guicomponents/GameDialogFactory.class new file mode 100644 index 0000000..bab04b5 Binary files /dev/null and b/build/classes/com/mathgame/guicomponents/GameDialogFactory.class differ diff --git a/build/classes/com/mathgame/math/Calculate.class b/build/classes/com/mathgame/math/Calculate.class new file mode 100644 index 0000000..5f94ec5 Binary files /dev/null and b/build/classes/com/mathgame/math/Calculate.class differ diff --git a/build/classes/com/mathgame/math/CompMover.class b/build/classes/com/mathgame/math/CompMover.class new file mode 100644 index 0000000..5bded6c Binary files /dev/null and b/build/classes/com/mathgame/math/CompMover.class differ diff --git a/build/classes/com/mathgame/math/MathGame$1.class b/build/classes/com/mathgame/math/MathGame$1.class new file mode 100644 index 0000000..650bcfb Binary files /dev/null and b/build/classes/com/mathgame/math/MathGame$1.class differ diff --git a/build/classes/com/mathgame/math/MathGame$2.class b/build/classes/com/mathgame/math/MathGame$2.class new file mode 100644 index 0000000..8c61df3 Binary files /dev/null and b/build/classes/com/mathgame/math/MathGame$2.class differ diff --git a/build/classes/com/mathgame/math/MathGame$GameState.class b/build/classes/com/mathgame/math/MathGame$GameState.class new file mode 100644 index 0000000..4786932 Binary files /dev/null and b/build/classes/com/mathgame/math/MathGame$GameState.class differ diff --git a/build/classes/com/mathgame/math/MathGame$Menu.class b/build/classes/com/mathgame/math/MathGame$Menu.class new file mode 100644 index 0000000..4b34b3a Binary files /dev/null and b/build/classes/com/mathgame/math/MathGame$Menu.class differ diff --git a/build/classes/com/mathgame/math/MathGame.class b/build/classes/com/mathgame/math/MathGame.class new file mode 100644 index 0000000..db90de2 Binary files /dev/null and b/build/classes/com/mathgame/math/MathGame.class differ diff --git a/build/classes/com/mathgame/math/ScoringSystem.class b/build/classes/com/mathgame/math/ScoringSystem.class new file mode 100644 index 0000000..1a9f697 Binary files /dev/null and b/build/classes/com/mathgame/math/ScoringSystem.class differ diff --git a/build/classes/com/mathgame/math/SoundManager$SoundType.class b/build/classes/com/mathgame/math/SoundManager$SoundType.class new file mode 100644 index 0000000..098b38f Binary files /dev/null and b/build/classes/com/mathgame/math/SoundManager$SoundType.class differ diff --git a/build/classes/com/mathgame/math/SoundManager.class b/build/classes/com/mathgame/math/SoundManager.class new file mode 100644 index 0000000..7d39e3b Binary files /dev/null and b/build/classes/com/mathgame/math/SoundManager.class differ diff --git a/build/classes/com/mathgame/math/TypeManager$Difficulty.class b/build/classes/com/mathgame/math/TypeManager$Difficulty.class new file mode 100644 index 0000000..5575c45 Binary files /dev/null and b/build/classes/com/mathgame/math/TypeManager$Difficulty.class differ diff --git a/build/classes/com/mathgame/math/TypeManager$GameType.class b/build/classes/com/mathgame/math/TypeManager$GameType.class new file mode 100644 index 0000000..e911084 Binary files /dev/null and b/build/classes/com/mathgame/math/TypeManager$GameType.class differ diff --git a/build/classes/com/mathgame/math/TypeManager.class b/build/classes/com/mathgame/math/TypeManager.class new file mode 100644 index 0000000..fa168a6 Binary files /dev/null and b/build/classes/com/mathgame/math/TypeManager.class differ diff --git a/build/classes/com/mathgame/math/Window$1.class b/build/classes/com/mathgame/math/Window$1.class new file mode 100644 index 0000000..08f6103 Binary files /dev/null and b/build/classes/com/mathgame/math/Window$1.class differ diff --git a/build/classes/com/mathgame/math/Window$2.class b/build/classes/com/mathgame/math/Window$2.class new file mode 100644 index 0000000..53b4cff Binary files /dev/null and b/build/classes/com/mathgame/math/Window$2.class differ diff --git a/build/classes/com/mathgame/math/Window$MathWindowListener.class b/build/classes/com/mathgame/math/Window$MathWindowListener.class new file mode 100644 index 0000000..645fc3c Binary files /dev/null and b/build/classes/com/mathgame/math/Window$MathWindowListener.class differ diff --git a/build/classes/com/mathgame/math/Window.class b/build/classes/com/mathgame/math/Window.class new file mode 100644 index 0000000..7195773 Binary files /dev/null and b/build/classes/com/mathgame/math/Window.class differ diff --git a/build/classes/com/mathgame/menus/HelpMenu.class b/build/classes/com/mathgame/menus/HelpMenu.class new file mode 100644 index 0000000..5a32bd1 Binary files /dev/null and b/build/classes/com/mathgame/menus/HelpMenu.class differ diff --git a/build/classes/com/mathgame/menus/HostMenu$1.class b/build/classes/com/mathgame/menus/HostMenu$1.class new file mode 100644 index 0000000..9d40474 Binary files /dev/null and b/build/classes/com/mathgame/menus/HostMenu$1.class differ diff --git a/build/classes/com/mathgame/menus/HostMenu.class b/build/classes/com/mathgame/menus/HostMenu.class new file mode 100644 index 0000000..740cb70 Binary files /dev/null and b/build/classes/com/mathgame/menus/HostMenu.class differ diff --git a/build/classes/com/mathgame/menus/LoginMenu.class b/build/classes/com/mathgame/menus/LoginMenu.class new file mode 100644 index 0000000..e7868eb Binary files /dev/null and b/build/classes/com/mathgame/menus/LoginMenu.class differ diff --git a/build/classes/com/mathgame/menus/MainMenu.class b/build/classes/com/mathgame/menus/MainMenu.class new file mode 100644 index 0000000..6f56d1e Binary files /dev/null and b/build/classes/com/mathgame/menus/MainMenu.class differ diff --git a/build/classes/com/mathgame/menus/MultiMenu$1.class b/build/classes/com/mathgame/menus/MultiMenu$1.class new file mode 100644 index 0000000..7df574a Binary files /dev/null and b/build/classes/com/mathgame/menus/MultiMenu$1.class differ diff --git a/build/classes/com/mathgame/menus/MultiMenu$GameCard$1.class b/build/classes/com/mathgame/menus/MultiMenu$GameCard$1.class new file mode 100644 index 0000000..70ed6ac Binary files /dev/null and b/build/classes/com/mathgame/menus/MultiMenu$GameCard$1.class differ diff --git a/build/classes/com/mathgame/menus/MultiMenu$GameCard.class b/build/classes/com/mathgame/menus/MultiMenu$GameCard.class new file mode 100644 index 0000000..f0d3e32 Binary files /dev/null and b/build/classes/com/mathgame/menus/MultiMenu$GameCard.class differ diff --git a/build/classes/com/mathgame/menus/MultiMenu.class b/build/classes/com/mathgame/menus/MultiMenu.class new file mode 100644 index 0000000..63a3cb9 Binary files /dev/null and b/build/classes/com/mathgame/menus/MultiMenu.class differ diff --git a/build/classes/com/mathgame/menus/RegisterMenu.class b/build/classes/com/mathgame/menus/RegisterMenu.class new file mode 100644 index 0000000..3866e97 Binary files /dev/null and b/build/classes/com/mathgame/menus/RegisterMenu.class differ diff --git a/build/classes/com/mathgame/network/Game.class b/build/classes/com/mathgame/network/Game.class new file mode 100644 index 0000000..e7a623d Binary files /dev/null and b/build/classes/com/mathgame/network/Game.class differ diff --git a/build/classes/com/mathgame/network/GameManager.class b/build/classes/com/mathgame/network/GameManager.class new file mode 100644 index 0000000..b983831 Binary files /dev/null and b/build/classes/com/mathgame/network/GameManager.class differ diff --git a/build/classes/com/mathgame/network/User.class b/build/classes/com/mathgame/network/User.class new file mode 100644 index 0000000..9f2ad62 Binary files /dev/null and b/build/classes/com/mathgame/network/User.class differ diff --git a/build/classes/com/mathgame/offline/TypeManagerO$Difficulty.class b/build/classes/com/mathgame/offline/TypeManagerO$Difficulty.class new file mode 100644 index 0000000..5ca28b1 Binary files /dev/null and b/build/classes/com/mathgame/offline/TypeManagerO$Difficulty.class differ diff --git a/build/classes/com/mathgame/offline/TypeManagerO$GameType.class b/build/classes/com/mathgame/offline/TypeManagerO$GameType.class new file mode 100644 index 0000000..f510a16 Binary files /dev/null and b/build/classes/com/mathgame/offline/TypeManagerO$GameType.class differ diff --git a/build/classes/com/mathgame/offline/TypeManagerO.class b/build/classes/com/mathgame/offline/TypeManagerO.class new file mode 100644 index 0000000..e7b1e7c Binary files /dev/null and b/build/classes/com/mathgame/offline/TypeManagerO.class differ diff --git a/build/classes/com/mathgame/panels/CardPanel.class b/build/classes/com/mathgame/panels/CardPanel.class new file mode 100644 index 0000000..fc918cc Binary files /dev/null and b/build/classes/com/mathgame/panels/CardPanel.class differ diff --git a/build/classes/com/mathgame/panels/HoldPanel.class b/build/classes/com/mathgame/panels/HoldPanel.class new file mode 100644 index 0000000..eab650d Binary files /dev/null and b/build/classes/com/mathgame/panels/HoldPanel.class differ diff --git a/build/classes/com/mathgame/panels/OperationPanel.class b/build/classes/com/mathgame/panels/OperationPanel.class new file mode 100644 index 0000000..4602631 Binary files /dev/null and b/build/classes/com/mathgame/panels/OperationPanel.class differ diff --git a/build/classes/com/mathgame/panels/SidePanel$1.class b/build/classes/com/mathgame/panels/SidePanel$1.class new file mode 100644 index 0000000..0c4d83d Binary files /dev/null and b/build/classes/com/mathgame/panels/SidePanel$1.class differ diff --git a/build/classes/com/mathgame/panels/SidePanel$SummaryDialog$1.class b/build/classes/com/mathgame/panels/SidePanel$SummaryDialog$1.class new file mode 100644 index 0000000..9d8b730 Binary files /dev/null and b/build/classes/com/mathgame/panels/SidePanel$SummaryDialog$1.class differ diff --git a/build/classes/com/mathgame/panels/SidePanel$SummaryDialog.class b/build/classes/com/mathgame/panels/SidePanel$SummaryDialog.class new file mode 100644 index 0000000..4e41ebe Binary files /dev/null and b/build/classes/com/mathgame/panels/SidePanel$SummaryDialog.class differ diff --git a/build/classes/com/mathgame/panels/SidePanel.class b/build/classes/com/mathgame/panels/SidePanel.class new file mode 100644 index 0000000..ce7bdd0 Binary files /dev/null and b/build/classes/com/mathgame/panels/SidePanel.class differ diff --git a/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog$1.class b/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog$1.class new file mode 100644 index 0000000..66aaec4 Binary files /dev/null and b/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog$1.class differ diff --git a/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog$2.class b/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog$2.class new file mode 100644 index 0000000..edad87b Binary files /dev/null and b/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog$2.class differ diff --git a/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog.class b/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog.class new file mode 100644 index 0000000..624a6fc Binary files /dev/null and b/build/classes/com/mathgame/panels/WorkspacePanel$AnswerDialog.class differ diff --git a/build/classes/com/mathgame/panels/WorkspacePanel.class b/build/classes/com/mathgame/panels/WorkspacePanel.class new file mode 100644 index 0000000..7263773 Binary files /dev/null and b/build/classes/com/mathgame/panels/WorkspacePanel.class differ diff --git a/build/classes/images/CardBar.png b/build/classes/images/CardBar.png new file mode 100644 index 0000000..7356244 Binary files /dev/null and b/build/classes/images/CardBar.png differ diff --git a/build/classes/images/CardBar1.png b/build/classes/images/CardBar1.png new file mode 100644 index 0000000..aaf9718 Binary files /dev/null and b/build/classes/images/CardBar1.png differ diff --git a/build/classes/images/DefaultButtonImage1.png b/build/classes/images/DefaultButtonImage1.png new file mode 100644 index 0000000..5ffea18 Binary files /dev/null and b/build/classes/images/DefaultButtonImage1.png differ diff --git a/build/classes/images/DefaultButtonImage2.png b/build/classes/images/DefaultButtonImage2.png new file mode 100644 index 0000000..b5d96c9 Binary files /dev/null and b/build/classes/images/DefaultButtonImage2.png differ diff --git a/build/classes/images/DefaultButtonImage3.png b/build/classes/images/DefaultButtonImage3.png new file mode 100644 index 0000000..6ada89f Binary files /dev/null and b/build/classes/images/DefaultButtonImage3.png differ diff --git a/build/classes/images/MathGames UML 1.pdf b/build/classes/images/MathGames UML 1.pdf new file mode 100644 index 0000000..0bee905 Binary files /dev/null and b/build/classes/images/MathGames UML 1.pdf differ diff --git a/build/classes/images/Operation bar.png b/build/classes/images/Operation bar.png new file mode 100644 index 0000000..d1659b6 Binary files /dev/null and b/build/classes/images/Operation bar.png differ diff --git a/build/classes/images/Operation bar1.png b/build/classes/images/Operation bar1.png new file mode 100644 index 0000000..475fc92 Binary files /dev/null and b/build/classes/images/Operation bar1.png differ diff --git a/build/classes/images/Screenshots/class1.jpg b/build/classes/images/Screenshots/class1.jpg new file mode 100644 index 0000000..05696d6 Binary files /dev/null and b/build/classes/images/Screenshots/class1.jpg differ diff --git a/build/classes/images/Screenshots/class2.jpg b/build/classes/images/Screenshots/class2.jpg new file mode 100644 index 0000000..2cfff92 Binary files /dev/null and b/build/classes/images/Screenshots/class2.jpg differ diff --git a/build/classes/images/Screenshots/gameplay.png b/build/classes/images/Screenshots/gameplay.png new file mode 100644 index 0000000..4e975f1 Binary files /dev/null and b/build/classes/images/Screenshots/gameplay.png differ diff --git a/build/classes/images/Screenshots/gamesettings.png b/build/classes/images/Screenshots/gamesettings.png new file mode 100644 index 0000000..4f47301 Binary files /dev/null and b/build/classes/images/Screenshots/gamesettings.png differ diff --git a/build/classes/images/Screenshots/login.jpg b/build/classes/images/Screenshots/login.jpg new file mode 100644 index 0000000..c1e2655 Binary files /dev/null and b/build/classes/images/Screenshots/login.jpg differ diff --git a/build/classes/images/Screenshots/menu.jpg b/build/classes/images/Screenshots/menu.jpg new file mode 100644 index 0000000..c63dd9c Binary files /dev/null and b/build/classes/images/Screenshots/menu.jpg differ diff --git a/build/classes/images/Thumbs.db b/build/classes/images/Thumbs.db new file mode 100644 index 0000000..35c8e6f Binary files /dev/null and b/build/classes/images/Thumbs.db differ diff --git a/build/classes/images/Workspace.png b/build/classes/images/Workspace.png new file mode 100644 index 0000000..d49d0d3 Binary files /dev/null and b/build/classes/images/Workspace.png differ diff --git a/build/classes/images/Workspace1.png b/build/classes/images/Workspace1.png new file mode 100644 index 0000000..1c0b80c Binary files /dev/null and b/build/classes/images/Workspace1.png differ diff --git a/build/classes/images/add.png b/build/classes/images/add.png new file mode 100644 index 0000000..789eeab Binary files /dev/null and b/build/classes/images/add.png differ diff --git a/build/classes/images/backMulti.png b/build/classes/images/backMulti.png new file mode 100644 index 0000000..a52865d Binary files /dev/null and b/build/classes/images/backMulti.png differ diff --git a/build/classes/images/backa.png b/build/classes/images/backa.png new file mode 100644 index 0000000..c2a6de8 Binary files /dev/null and b/build/classes/images/backa.png differ diff --git a/build/classes/images/backb.png b/build/classes/images/backb.png new file mode 100644 index 0000000..d9d9039 Binary files /dev/null and b/build/classes/images/backb.png differ diff --git a/build/classes/images/background.png b/build/classes/images/background.png new file mode 100644 index 0000000..ff3ab3c Binary files /dev/null and b/build/classes/images/background.png differ diff --git a/build/classes/images/background2.png b/build/classes/images/background2.png new file mode 100644 index 0000000..a52865d Binary files /dev/null and b/build/classes/images/background2.png differ diff --git a/build/classes/images/card holder.png b/build/classes/images/card holder.png new file mode 100644 index 0000000..52b19b4 Binary files /dev/null and b/build/classes/images/card holder.png differ diff --git a/build/classes/images/card holder1.png b/build/classes/images/card holder1.png new file mode 100644 index 0000000..b5e78ef Binary files /dev/null and b/build/classes/images/card holder1.png differ diff --git a/build/classes/images/control bar.png b/build/classes/images/control bar.png new file mode 100644 index 0000000..53cbed4 Binary files /dev/null and b/build/classes/images/control bar.png differ diff --git a/build/classes/images/control bar1.png b/build/classes/images/control bar1.png new file mode 100644 index 0000000..cf99562 Binary files /dev/null and b/build/classes/images/control bar1.png differ diff --git a/build/classes/images/divide.png b/build/classes/images/divide.png new file mode 100644 index 0000000..431813e Binary files /dev/null and b/build/classes/images/divide.png differ diff --git a/build/classes/images/enter.png b/build/classes/images/enter.png new file mode 100644 index 0000000..bf62a76 Binary files /dev/null and b/build/classes/images/enter.png differ diff --git a/build/classes/images/epsilon.png b/build/classes/images/epsilon.png new file mode 100644 index 0000000..8be5fdb Binary files /dev/null and b/build/classes/images/epsilon.png differ diff --git a/build/classes/images/exponent.png b/build/classes/images/exponent.png new file mode 100644 index 0000000..a8f566f Binary files /dev/null and b/build/classes/images/exponent.png differ diff --git a/build/classes/images/multiply.png b/build/classes/images/multiply.png new file mode 100644 index 0000000..28ce90b Binary files /dev/null and b/build/classes/images/multiply.png differ diff --git a/build/classes/images/mute.png b/build/classes/images/mute.png new file mode 100644 index 0000000..6d84106 Binary files /dev/null and b/build/classes/images/mute.png differ diff --git a/build/classes/images/sound.png b/build/classes/images/sound.png new file mode 100644 index 0000000..fc4203b Binary files /dev/null and b/build/classes/images/sound.png differ diff --git a/build/classes/images/subtract.png b/build/classes/images/subtract.png new file mode 100644 index 0000000..8cc0331 Binary files /dev/null and b/build/classes/images/subtract.png differ diff --git a/src/images/Decimals.xlsx b/build/classes/spreadsheets/Decimals.xlsx similarity index 100% rename from src/images/Decimals.xlsx rename to build/classes/spreadsheets/Decimals.xlsx diff --git a/src/images/Decimals_Easy.xlsx b/build/classes/spreadsheets/Decimals_Easy.xlsx similarity index 100% rename from src/images/Decimals_Easy.xlsx rename to build/classes/spreadsheets/Decimals_Easy.xlsx diff --git a/src/images/Decimals_Hard.xlsx b/build/classes/spreadsheets/Decimals_Hard.xlsx similarity index 100% rename from src/images/Decimals_Hard.xlsx rename to build/classes/spreadsheets/Decimals_Hard.xlsx diff --git a/src/images/Decimals_Medium.xlsx b/build/classes/spreadsheets/Decimals_Medium.xlsx similarity index 100% rename from src/images/Decimals_Medium.xlsx rename to build/classes/spreadsheets/Decimals_Medium.xlsx diff --git a/build/classes/spreadsheets/Exponents.xlsx b/build/classes/spreadsheets/Exponents.xlsx new file mode 100644 index 0000000..1c4a268 Binary files /dev/null and b/build/classes/spreadsheets/Exponents.xlsx differ diff --git a/src/images/Fractions.xlsx b/build/classes/spreadsheets/Fractions.xlsx similarity index 100% rename from src/images/Fractions.xlsx rename to build/classes/spreadsheets/Fractions.xlsx diff --git a/src/images/Fractions_Easy.xlsx b/build/classes/spreadsheets/Fractions_Easy.xlsx similarity index 100% rename from src/images/Fractions_Easy.xlsx rename to build/classes/spreadsheets/Fractions_Easy.xlsx diff --git a/src/images/Fractions_Hard.xlsx b/build/classes/spreadsheets/Fractions_Hard.xlsx similarity index 100% rename from src/images/Fractions_Hard.xlsx rename to build/classes/spreadsheets/Fractions_Hard.xlsx diff --git a/src/images/Fractions_Medium.xlsx b/build/classes/spreadsheets/Fractions_Medium.xlsx similarity index 100% rename from src/images/Fractions_Medium.xlsx rename to build/classes/spreadsheets/Fractions_Medium.xlsx diff --git a/src/images/Integers.xlsx b/build/classes/spreadsheets/Integers.xlsx similarity index 100% rename from src/images/Integers.xlsx rename to build/classes/spreadsheets/Integers.xlsx diff --git a/build/classes/spreadsheets/Logarithms.xlsx b/build/classes/spreadsheets/Logarithms.xlsx new file mode 100644 index 0000000..7400a24 Binary files /dev/null and b/build/classes/spreadsheets/Logarithms.xlsx differ diff --git a/dist/MathGame.jar b/dist/MathGame.jar new file mode 100644 index 0000000..c355123 Binary files /dev/null and b/dist/MathGame.jar differ diff --git a/dist/README.TXT b/dist/README.TXT new file mode 100644 index 0000000..931f73b --- /dev/null +++ b/dist/README.TXT @@ -0,0 +1,32 @@ +======================== +BUILD OUTPUT DESCRIPTION +======================== + +When you build an Java application project that has a main class, the IDE +automatically copies all of the JAR +files on the projects classpath to your projects dist/lib folder. The IDE +also adds each of the JAR files to the Class-Path element in the application +JAR files manifest file (MANIFEST.MF). + +To run the project from the command line, go to the dist folder and +type the following: + +java -jar "MathGame.jar" + +To distribute this project, zip up the dist folder (including the lib folder) +and distribute the ZIP file. + +Notes: + +* If two JAR files on the project classpath have the same name, only the first +JAR file is copied to the lib folder. +* Only JAR files are copied to the lib folder. +If the classpath contains other types of files or folders, these files (folders) +are not copied. +* If a library on the projects classpath also has a Class-Path element +specified in the manifest,the content of the Class-Path element has to be on +the projects runtime path. +* To set a main class in a standard Java project, right-click the project node +in the Projects window and choose Properties. Then click Run and enter the +class name in the Main Class field. Alternatively, you can manually type the +class name in the manifest Main-Class element. diff --git a/dist/README.md b/dist/README.md new file mode 100644 index 0000000..8e00d03 --- /dev/null +++ b/dist/README.md @@ -0,0 +1,12 @@ +Math Game +========= + +A math game Java GUI program made with Java Swing. + +This program is meant to encourage learning math by presenting math problems in a fun and intuitive way. + +---------------------------------------------------- +Created by students at the Middlesex County Academy for Science, Mathematics, and Engineering Technologies +located in Edison, NJ + +Visit the game at http://www.mcalearning.com/ diff --git a/dist/dom4j-2.0.0-ALPHA-2.jar b/dist/dom4j-2.0.0-ALPHA-2.jar new file mode 100644 index 0000000..95da51b Binary files /dev/null and b/dist/dom4j-2.0.0-ALPHA-2.jar differ diff --git a/dist/lib/dom4j-2.0.0-ALPHA-2.jar b/dist/lib/dom4j-2.0.0-ALPHA-2.jar new file mode 100644 index 0000000..95da51b Binary files /dev/null and b/dist/lib/dom4j-2.0.0-ALPHA-2.jar differ diff --git a/dist/lib/mysql-connector-java-5.1.38-bin.jar b/dist/lib/mysql-connector-java-5.1.38-bin.jar new file mode 100644 index 0000000..377470a Binary files /dev/null and b/dist/lib/mysql-connector-java-5.1.38-bin.jar differ diff --git a/dist/lib/poi-3.9-20121203.jar b/dist/lib/poi-3.9-20121203.jar new file mode 100644 index 0000000..0f46288 Binary files /dev/null and b/dist/lib/poi-3.9-20121203.jar differ diff --git a/dist/lib/poi-ooxml-3.9-20121203.jar b/dist/lib/poi-ooxml-3.9-20121203.jar new file mode 100644 index 0000000..8792d46 Binary files /dev/null and b/dist/lib/poi-ooxml-3.9-20121203.jar differ diff --git a/dist/lib/poi-ooxml-schemas-3.9-20121203.jar b/dist/lib/poi-ooxml-schemas-3.9-20121203.jar new file mode 100644 index 0000000..eda4ef4 Binary files /dev/null and b/dist/lib/poi-ooxml-schemas-3.9-20121203.jar differ diff --git a/dist/lib/xbean.jar b/dist/lib/xbean.jar new file mode 100644 index 0000000..d1b6627 Binary files /dev/null and b/dist/lib/xbean.jar differ diff --git a/dist/mysql-connector-java-5.1.38-bin.jar b/dist/mysql-connector-java-5.1.38-bin.jar new file mode 100644 index 0000000..377470a Binary files /dev/null and b/dist/mysql-connector-java-5.1.38-bin.jar differ diff --git a/dist/poi-3.9-20121203.jar b/dist/poi-3.9-20121203.jar new file mode 100644 index 0000000..0f46288 Binary files /dev/null and b/dist/poi-3.9-20121203.jar differ diff --git a/dist/poi-ooxml-3.9-20121203.jar b/dist/poi-ooxml-3.9-20121203.jar new file mode 100644 index 0000000..8792d46 Binary files /dev/null and b/dist/poi-ooxml-3.9-20121203.jar differ diff --git a/dist/poi-ooxml-schemas-3.9-20121203.jar b/dist/poi-ooxml-schemas-3.9-20121203.jar new file mode 100644 index 0000000..eda4ef4 Binary files /dev/null and b/dist/poi-ooxml-schemas-3.9-20121203.jar differ diff --git a/dist/servlet-api.jar b/dist/servlet-api.jar new file mode 100644 index 0000000..9dcb2f5 Binary files /dev/null and b/dist/servlet-api.jar differ diff --git a/dist/test.txt b/dist/test.txt new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/dist/test.txt @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/dist/xbean.jar b/dist/xbean.jar new file mode 100644 index 0000000..d1b6627 Binary files /dev/null and b/dist/xbean.jar differ diff --git a/mysql-connector-java-5.1.22-bin.jar b/mysql-connector-java-5.1.22-bin.jar deleted file mode 100644 index a50424d..0000000 Binary files a/mysql-connector-java-5.1.22-bin.jar and /dev/null differ diff --git a/mysql-connector-java-5.1.23-bin.jar b/mysql-connector-java-5.1.23-bin.jar deleted file mode 100644 index 9bd1fde..0000000 Binary files a/mysql-connector-java-5.1.23-bin.jar and /dev/null differ diff --git a/mysql-connector-java-5.1.26-bin.jar b/mysql-connector-java-5.1.26-bin.jar deleted file mode 100644 index bf1e933..0000000 Binary files a/mysql-connector-java-5.1.26-bin.jar and /dev/null differ diff --git a/mysql-connector-java-5.1.38-bin.jar b/mysql-connector-java-5.1.38-bin.jar new file mode 100644 index 0000000..377470a Binary files /dev/null and b/mysql-connector-java-5.1.38-bin.jar differ diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..97f7239 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1403 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/build-native.xml b/nbproject/build-native.xml new file mode 100644 index 0000000..1aa10a0 --- /dev/null +++ b/nbproject/build-native.xml @@ -0,0 +1,951 @@ + + + + + + + + + Native Packager Ant calls based on SE support in JavaFX packager + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + self.addMappedName( + (source.indexOf("jfxrt.jar") >= 0) || + (source.indexOf("deploy.jar") >= 0) || + (source.indexOf("javaws.jar") >= 0) || + (source.indexOf("plugin.jar") >= 0) + ? "" : source + ); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..f44e746 --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=9e79a357 +build.xml.script.CRC32=1ee1bbf5 +build.xml.stylesheet.CRC32=8064a381@1.79.1.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=9e79a357 +nbproject/build-impl.xml.script.CRC32=51191858 +nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48 diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties new file mode 100644 index 0000000..3bc5246 --- /dev/null +++ b/nbproject/private/private.properties @@ -0,0 +1,6 @@ +compile.on.save=true +do.depend=false +do.jar=true +javac.debug=true +javadoc.preview=true +user.properties.file=C:\\Users\\Zarir Hamza\\AppData\\Roaming\\NetBeans\\8.1\\build.properties diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..c2f4a1a --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,98 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=MathGame +application.vendor=Zarir Hamza +auxiliary.org-netbeans-modules-projectimport-eclipse-core.key=src=src;file=dom4j-2.0.0-ALPHA-2.jar;file=poi-3.9-20121203.jar;file=poi-ooxml-3.9-20121203.jar;file=poi-ooxml-schemas-3.9-20121203.jar;file=xbean.jar;file=mysql-connector-java-5.1.38-bin.jar;output=bin; +auxiliary.org-netbeans-modules-projectimport-eclipse-core.project=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy +auxiliary.org-netbeans-modules-projectimport-eclipse-core.timestamp=1457310420000 +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +copylibs.excludes=${javafx.classpath.extension} +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/MathGame.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.dom4j-2.0.0-ALPHA-2.jar=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy\\dom4j-2.0.0-ALPHA-2.jar +file.reference.Math-Game-develop_-_Copy-src=../../../Desktop/Math-Game-develop - Copy/src +file.reference.mysql-connector-java-5.1.38-bin.jar=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy\\mysql-connector-java-5.1.38-bin.jar +file.reference.poi-3.9-20121203.jar=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy\\poi-3.9-20121203.jar +file.reference.poi-ooxml-3.9-20121203.jar=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy\\poi-ooxml-3.9-20121203.jar +file.reference.poi-ooxml-schemas-3.9-20121203.jar=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy\\poi-ooxml-schemas-3.9-20121203.jar +file.reference.xbean.jar=C:\\Users\\Zarir Hamza\\Desktop\\Math-Game-develop - Copy\\xbean.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.dom4j-2.0.0-ALPHA-2.jar}:\ + ${file.reference.poi-3.9-20121203.jar}:\ + ${file.reference.poi-ooxml-3.9-20121203.jar}:\ + ${file.reference.poi-ooxml-schemas-3.9-20121203.jar}:\ + ${file.reference.xbean.jar}:\ + ${file.reference.mysql-connector-java-5.1.38-bin.jar}:\ + ${javafx.classpath.extension} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=true +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +javafx.classpath.extension=\ + ${java.home}/lib/javaws.jar:\ + ${java.home}/lib/deploy.jar:\ + ${java.home}/lib/plugin.jar +keep.javafx.runtime.on.classpath=true +main.class=com.mathgame.math.Window +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +native.bundling.enabled=true +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=${file.reference.Math-Game-develop_-_Copy-src} diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..9e8e1d3 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,16 @@ + + + org.netbeans.modules.java.j2seproject + + + + + + MathGame + + + + + + + diff --git a/src/audio/lose.wav b/src/audio/lose.wav new file mode 100644 index 0000000..a1bdb17 Binary files /dev/null and b/src/audio/lose.wav differ diff --git a/src/audio/wait.wav b/src/audio/wait.wav new file mode 100644 index 0000000..49872c0 Binary files /dev/null and b/src/audio/wait.wav differ diff --git a/src/audio/win.wav b/src/audio/win.wav new file mode 100644 index 0000000..e6fbb4e Binary files /dev/null and b/src/audio/win.wav differ diff --git a/src/com/mathgame/cardmanager/Move.java b/src/com/mathgame/cardmanager/Move.java index e72ec54..34cc203 100644 --- a/src/com/mathgame/cardmanager/Move.java +++ b/src/com/mathgame/cardmanager/Move.java @@ -1,5 +1,7 @@ package com.mathgame.cardmanager; +//David K. was here and then he wasn't.... + import com.mathgame.cards.NumberCard; import com.mathgame.cards.OperationCard; diff --git a/src/com/mathgame/cardmanager/UndoButton.java b/src/com/mathgame/cardmanager/UndoButton.java index 9cea285..f26c58f 100644 --- a/src/com/mathgame/cardmanager/UndoButton.java +++ b/src/com/mathgame/cardmanager/UndoButton.java @@ -4,26 +4,25 @@ import com.mathgame.cards.NumberCard; import com.mathgame.cards.OperationCard; +import com.mathgame.guicomponents.GameButton; import com.mathgame.math.MathGame; /** * The UndoButton class represents the undo button, which uses the MoveTracker class * @author Roland */ -public class UndoButton extends JButton { +public class UndoButton extends GameButton { private static final long serialVersionUID = -1610472234274569185L; - static MathGame mathGame; MoveTracker tracker; /** * @param text - The text to be displayed on the UndoButton * @param mathGame - THe current mathGame instance */ - public UndoButton(String text, MathGame game) { - this.setText(text); - mathGame = game; + public UndoButton(String text) { + super(text); tracker = new MoveTracker(); } diff --git a/src/com/mathgame/cards/ImageGenerator.java b/src/com/mathgame/cards/ImageGenerator.java index 6b0586d..f3070e3 100644 --- a/src/com/mathgame/cards/ImageGenerator.java +++ b/src/com/mathgame/cards/ImageGenerator.java @@ -10,6 +10,8 @@ import javax.imageio.ImageIO; +import com.mathgame.math.MathGame; + /** * The ImageGenerator class generates images for cards when given a mathematical expression. * It is intended to support integers, decimals, fractions, exponents, and (in the future) logarithms @@ -19,9 +21,6 @@ public class ImageGenerator { private BufferedImage img; private Graphics2D g2d; - private static final Font sansSerif24 = new Font("SansSerif", Font.PLAIN, 24); - private static final Font sansSerif20 = new Font("SansSerif", Font.PLAIN, 20); - private static final Font sansSerif16 = new Font("SansSerif", Font.PLAIN, 16); private String imgFile; private File outf; @@ -50,10 +49,10 @@ public BufferedImage renderExpression(String e) { e = e.trim(); // Remove leading and trailing whitespaces g2d = img.createGraphics(); - FontMetrics metrics24 = g2d.getFontMetrics(sansSerif24); - FontMetrics metrics20 = g2d.getFontMetrics(sansSerif20); - FontMetrics metrics16 = g2d.getFontMetrics(sansSerif16); - g2d.setFont(sansSerif24); + FontMetrics metrics24 = g2d.getFontMetrics(MathGame.eurostile24); + FontMetrics metrics20 = g2d.getFontMetrics(MathGame.eurostile20); + FontMetrics metrics16 = g2d.getFontMetrics(MathGame.eurostile16); + g2d.setFont(MathGame.eurostile24); g2d.setColor(Color.white); g2d.fillRect(0, 0, width, height); g2d.setColor(Color.black); @@ -101,11 +100,11 @@ public BufferedImage renderExpression(String e) { g2d.drawString(hold[0], (width / 2) - (metrics24.stringWidth(hold[0]) / 2) - (metrics16.stringWidth(hold[1]) / 4), (height / 2) + (metrics24.getHeight() / 2)); - g2d.setFont(sansSerif16); + g2d.setFont(MathGame.eurostile16); g2d.drawString(hold[1], (width / 2) + (metrics24.stringWidth(hold[0]) / 2) - (metrics16.stringWidth(hold[1]) / 4), (height / 2) - (metrics24.getHeight() / 2) + (metrics16.getHeight() / 2)); - g2d.setFont(sansSerif24); + g2d.setFont(MathGame.eurostile24); } else if (e.contains("_") && e.contains("(") && e.contains(")")) { //This expression contains a logarithm of the form: log_x(n) @@ -125,20 +124,20 @@ public BufferedImage renderExpression(String e) { hold[2] = hold[2].substring(0, hold[2].length() - 1); } - g2d.setFont(sansSerif20); + g2d.setFont(MathGame.eurostile20); g2d.drawString(hold[0], (width / 2) - ((metrics20.stringWidth(hold[0]) + metrics16.stringWidth(hold[1]) + metrics20.stringWidth(hold[2])) / 2), (height / 2) + (metrics20.getHeight() / 2)); - g2d.setFont(sansSerif16); + g2d.setFont(MathGame.eurostile16); g2d.drawString(hold[1], (width / 2) - ((metrics20.stringWidth(hold[0]) + metrics16.stringWidth(hold[1]) + metrics20.stringWidth(hold[2])) / 2) + metrics20.stringWidth(hold[0]), (height / 2) + (metrics20.getHeight() / 2) + (metrics16.getHeight() / 2)); - g2d.setFont(sansSerif20); + g2d.setFont(MathGame.eurostile20); g2d.drawString(hold[2], (width / 2) - ((metrics20.stringWidth(hold[0]) + metrics16.stringWidth(hold[1]) + metrics20.stringWidth(hold[2])) / 2) + metrics20.stringWidth(hold[0]) + metrics16.stringWidth(hold[1]), (height / 2) + (metrics20.getHeight() / 2)); - g2d.setFont(sansSerif24); + g2d.setFont(MathGame.eurostile24); } else if(e.contains(".")) { // The expression contains a decimal @@ -164,6 +163,8 @@ public BufferedImage renderExpression(String e) { ImageIO.write(img, "png", outf); } catch (IOException ioe) { ioe.printStackTrace(); + } catch (Exception e1){ + e1.printStackTrace(); } return img; diff --git a/src/com/mathgame/cards/NumberCard.java b/src/com/mathgame/cards/NumberCard.java index 2b276cc..e3a1426 100644 --- a/src/com/mathgame/cards/NumberCard.java +++ b/src/com/mathgame/cards/NumberCard.java @@ -18,7 +18,7 @@ public class NumberCard extends JLabel { private static final long serialVersionUID = -4999587614115223052L; - private String value; + private double value; private String strValue; private int width = 80; private int height = 100; @@ -47,8 +47,8 @@ public NumberCard() { * Creates a new NumberCard, displaying the given value (a double) */ public NumberCard (double n) { - n = round(n); // The value must be rounded to avoid errors when comparing value! - value = Double.toString(n); + //n = round(n); // The value must be rounded to avoid errors when comparing value! + value = n; strValue = Double.toString(n); // this.setText(String.valueOf(n)); @@ -69,7 +69,7 @@ public NumberCard (double n) { */ public NumberCard(String s) { // The value of the expression is evaluated before being stored as a string - value = String.valueOf(parseNumFromText(s)); + value = parseNumFromText(s); strValue = s; // Meanwhile, the original expression is stored too // this.setText(s); @@ -105,69 +105,38 @@ public void setHome(String home) { * @return The value of the expression (as a double) */ public static double parseNumFromText(String s){ - - double ans = 0; - - // The two separate numbers from the String s - double n1 = -1; - double n2 = -1; - - int end1 = -1; // Where the end of the 1st substring is - int end2 = -1; // Where the start of the 2nd substring is - - if (s.length() == 1) { - end1 = 0; + System.out.println("parsing: "+s); + if(s.contains(".")) {//probably a decimal, but no log_ included + return Double.valueOf(s); } - - for (int i = 0; i < s.length(); i++) { - char current = s.charAt(i); - if (!Character.isDigit(current)) { - // If the current character is not a digit - - if (current == '-') { - // Continue if the character is just a minus sign - continue; - } - - if (end1 == -1) { - end1 = i; - System.out.println("substring(parse) " + s.substring(0, end1)); - n1 = Double.valueOf(s.substring(0, end1)); - } - } else { - if (end1 != -1) { - end2 = i; - System.out.println("substring(parse) " + s.substring(end2, s.length())); - n2 = Double.valueOf(s.substring(end2, s.length())); - break; - } - } + else if(s.contains("/")) {// The expression contains a fraction + String hold[] = s.split("/"); // Splits the expression into two components + + hold[0] = hold[0].trim(); // The numerator + hold[1] = hold[1].trim(); // The denominator + return Double.valueOf(hold[0])/Double.valueOf(hold[1]); } - - String foundOp = ""; - System.out.println("end1 " + end1); - System.out.println("end2 " + end2); - if (end2 != -1) { - // An operator was encountered - foundOp = s.substring(end1, end2); + else if(s.contains("^")) {// The expression contains an exponent + String hold[] = s.split("\\^"); + + hold[0] = hold[0].trim(); // The base + hold[1] = hold[1].trim(); // The power + + return Math.pow(Double.valueOf(hold[0]), Double.valueOf(hold[1])); } - - System.out.println("substring(parse) " + foundOp); - System.out.println("entered s : " + s); - - if (foundOp.equals("/")) { - ans = n1/n2; - } else if (foundOp.equals("your op here")) { - System.out.println("nothing"); - } else { - // Just a normal number - ans = Double.valueOf(s); + else if(s.contains("_") && s.contains("(") && s.contains(")")) { + //This expression contains a logarithm of the form: log_x(n) + + String hold[] = s.split("[_()]"); // Splits the expression into three parts + + hold[0] = hold[0].trim(); // The word "log" + hold[1] = hold[1].trim(); // The base + hold[2] = hold[2].trim(); // The number (n) whose logarithm is being found + + return Math.log10(Double.valueOf(hold[2]))/Math.log10(Double.valueOf(hold[1])); } - ans = round(ans); // The value must be rounded to avoid errors when comparing value! - - System.out.println("sub answer(parse) " + ans); - return ans; + return Integer.valueOf(s);//nothing? it's probably an integer } /** @@ -180,7 +149,7 @@ public static double round (double n) { double q = n / MathGame.epsilon; - q = Math.floor(q + 0.5); // Round to nearest integer + q = Math.floor(q + 0.05); // Round to nearest integer n = q * MathGame.epsilon; return n; @@ -189,14 +158,14 @@ public static double round (double n) { /** * @return The actual value of the NumberCard */ - public String getValue() { + public double getValue() { return value; } /** * @param value - The (actual) value to set */ - public void setValue(String value) { + public void setValue(double value) { this.value = value; } diff --git a/src/com/mathgame/cards/OperationCard.java b/src/com/mathgame/cards/OperationCard.java index 5eeee4e..077bb45 100644 --- a/src/com/mathgame/cards/OperationCard.java +++ b/src/com/mathgame/cards/OperationCard.java @@ -49,7 +49,7 @@ public void setOperation(String operation) { * @param mathGame * @param operation - The operation */ - public OperationCard (MathGame mathGame, String operation) { + public OperationCard (String operation) { String imageFile = null; if (operation.equals("add")) { imageFile = "add.png"; @@ -59,14 +59,14 @@ public OperationCard (MathGame mathGame, String operation) { imageFile = "multiply.png"; } else if (operation.equals("divide")) { imageFile = "divide.png"; - } else { + } else if (operation.equals("exponent")) { + imageFile = "exponent.png"; + } else { System.err.println("Invalid operation"); } this.operation = operation; - // Image background = mathGame.getImage(mathGame.getDocumentBase(), "images/"+imageFile); - ImageIcon icon = new ImageIcon(OperationPanel.class.getResource("/images/"+imageFile)); this.setIcon(icon); diff --git a/src/com/mathgame/cards/ValidationBox.java b/src/com/mathgame/cards/ValidationBox.java index 6d40295..9b0d41c 100644 --- a/src/com/mathgame/cards/ValidationBox.java +++ b/src/com/mathgame/cards/ValidationBox.java @@ -47,12 +47,12 @@ public ValidationBox(NumberCard card) { @Override public void changedUpdate(DocumentEvent e) { - System.out.println("change update"); + //System.out.println("change update"); } @Override public void insertUpdate(DocumentEvent arg0) { - System.out.println("insert update"); + //System.out.println("insert update"); if(checkCard()) { setBackground(Color.green); } else if(getText().equals("")) { @@ -64,7 +64,7 @@ public void insertUpdate(DocumentEvent arg0) { @Override public void removeUpdate(DocumentEvent arg0) { - System.out.println("delete update"); + //System.out.println("delete update"); if(checkCard()) { setBackground(Color.green); } else if(getText().equals("")) { @@ -82,21 +82,21 @@ public void removeUpdate(DocumentEvent arg0) { * @return Whether the input matches the value (true) or not */ public boolean checkCard() { - System.out.println("this text " + this.getText()); - System.out.println("card text " + numCard.getValue()); - String ans = numCard.getValue(); + //System.out.println("this text " + this.getText()); + //System.out.println("card text " + numCard.getValue()); + double ans = numCard.getValue(); // Alternative method of verifying value try { - if (Math.abs(Double.parseDouble(this.getText()) - Double.parseDouble(ans)) < EPSILON) { - System.out.println("true"); + if (Math.abs(Double.parseDouble(this.getText()) - ans) < EPSILON) { + //System.out.println("true"); return true; } else { - System.out.println("false"); + //System.out.println("false"); return false; } } catch(NumberFormatException e) { - System.out.println("false"); + //System.out.println("false"); return false; } diff --git a/src/com/mathgame/database/GameAccess.java b/src/com/mathgame/database/GameAccess.java index d3cd0cd..7110b6d 100644 --- a/src/com/mathgame/database/GameAccess.java +++ b/src/com/mathgame/database/GameAccess.java @@ -5,8 +5,13 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; +import java.util.Arrays; import java.sql.Connection; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.MathGame; import com.mathgame.network.GameManager; @@ -16,7 +21,6 @@ */ public class GameAccess extends MySQLAccess { - static MathGame mathGame; private Connection connection; @SuppressWarnings("unused") @@ -27,26 +31,25 @@ public class GameAccess extends MySQLAccess { private ArrayList onlineUsers = new ArrayList(); - public GameAccess(MathGame game, Connection conn){ - mathGame = game; + public GameAccess(Connection conn){ connection = conn; } /** * Adds a user to the list of online users */ - public void addUser() { + public void addOnlineUser() { try { statement = connection.createStatement(); } catch (SQLException e) { e.printStackTrace(); } - System.out.println("name " + mathGame.getUser().getName()); + System.out.println("name " + MathGame.getUser().getName()); try { statement.executeUpdate("INSERT INTO sofiav_mathgame.online_users (ID, Name)" + - " VALUES (NULL, '" + mathGame.getUser().getName() + "')"); + " VALUES (NULL, '" + MathGame.getUser().getName() + "')"); } catch (SQLException e) { e.printStackTrace(); @@ -57,7 +60,7 @@ public void addUser() { * Removes a user from the list of online users * @param c - The Connection to the database */ - public void removeUser(Connection c) { + public void removeOnlineUser(Connection c) { // Why does a Connection object need to be passed? try { @@ -66,11 +69,11 @@ public void removeUser(Connection c) { e.printStackTrace(); } - System.out.println("removing name: " + mathGame.getUser().getName()); + System.out.println("removing name: " + MathGame.getUser().getName()); try { statement.executeUpdate("DELETE FROM sofiav_mathgame.online_users " + - "WHERE sofiav_mathgame.online_users.Name = '" + mathGame.getUser().getName() + "'"); + "WHERE sofiav_mathgame.online_users.Name = '" + MathGame.getUser().getName() + "'"); } catch (SQLException e) { e.printStackTrace(); @@ -83,19 +86,19 @@ public void removeUser(Connection c) { * Retrieves all user data from the database * @throws Exception */ - public ArrayList getUsers() throws Exception + public ArrayList getUsers() { // System.out.println(super.mathGame.getCursor()); - @SuppressWarnings("unused") + /*@SuppressWarnings("unused") String gameType; //TODO The variable is initialized but never used if (mathGame != null) { - gameType = mathGame.getTypeManager().getType().toString().toLowerCase(); + gameType = MathGame.getTypeManager().getType().toString().toLowerCase(); } else { gameType = "integers"; - } + }*/ try { statement = connection.createStatement(); @@ -112,19 +115,89 @@ public ArrayList getUsers() throws Exception } return onlineUsers; - } catch (Exception e) { + } catch (SQLException e) { // System.out.println("SQLException: " + e.getMessage()); - - if (e.getMessage().equals("No operations allowed after connection closed.")) { - if (!mathGame.getMySQLAccess().connect()) { - throw new Exception("couldn't connect"); - } - else { - System.out.println("CONNECTED ONCE AGAIN"); + System.out.println("STATE: " + e.getSQLState()); + if (e.getMessage().equals("No operations allowed after connection closed.") || e.getMessage().equals("Communications link failure")) { + MathGame.dbConnected = false; + System.err.println("Couldn't connect"); + if(MathGame.getMySQLAccess().displayUserConnectAgain() == true) + { GameManager.getMatchesAccess().reconnectStatement(); } + + } + return null; + } + } + + public boolean checkUserLogin(String username, char[] p){ + boolean isValid = false; + + if (MathGame.getMySQLAccess().getConnection() == null) { + MathGame.getMySQLAccess().connect(); + } + try { + statement = MathGame.getMySQLAccess().connection.createStatement(); + } catch (SQLException e) { + e.printStackTrace(); + } + username = username.toLowerCase(); + + + try { + resultSet = statement.executeQuery("select * from sofiav_mathgame.users where Username = '" + username + "'"); + if(resultSet.isBeforeFirst())//Will only be before the first row if the result set returns anything + { + resultSet.next(); + String pass = resultSet.getString("Password"); + //System.out.println("db pass: " + pass.toCharArray()); + System.out.println("entered pass: " + new String(p)); + if (Arrays.equals(p, pass.toCharArray())) + isValid = true; + } + + } catch (SQLException e) { + // TODO Auto-generated catch block + + if(e.getSQLState().equals("08S01")) + { + GameDialogFactory.showGameMessageDialog(new JPanel(), "Error", "Could not connect", GameDialogFactory.OK); + System.out.println("Could not connect to network"); + MathGame.dbConnected = false; } - throw e; + else + e.printStackTrace(); + + } + + + return isValid; + } + + + /** + * Adds a user to the list of online users + */ + public void registerUser(String username, String password) { + try { + statement = MathGame.getMySQLAccess().connection.createStatement(); + } catch (SQLException e) { + e.printStackTrace(); + } + username = username.toLowerCase(); + + System.out.println("name " + username); + System.out.println("password " + password); + + try { + statement.executeUpdate("INSERT INTO sofiav_mathgame.users (ID, Username, Password)" + + " VALUES (NULL, '" + username + "', '" + password + "')"); + + } catch (SQLException e) { + e.printStackTrace(); } } + + } diff --git a/src/com/mathgame/database/MatchesAccess.java b/src/com/mathgame/database/MatchesAccess.java index 4af558f..2e44a7d 100644 --- a/src/com/mathgame/database/MatchesAccess.java +++ b/src/com/mathgame/database/MatchesAccess.java @@ -7,8 +7,15 @@ import java.sql.Statement; import java.util.ArrayList; +import javax.swing.JPanel; + +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.MathGame; +import com.mathgame.menus.HostMenu; +import com.mathgame.menus.MultiMenu; import com.mathgame.network.Game; +import com.mathgame.network.GameManager; +import javax.swing.JOptionPane; /** * The MatchesAccess class handles interactions with the online matches table @@ -18,7 +25,6 @@ public class MatchesAccess extends MySQLAccess { private int matchNum = -1; - static MathGame mathGame; private Connection connection; private Statement statement = null; @@ -26,12 +32,10 @@ public class MatchesAccess extends MySQLAccess { private PreparedStatement preparedStatement = null; // private ResultSet resultSet = null; - public MatchesAccess(MathGame game, Connection c){ - mathGame = game; - mathGame.getAlignmentX(); //TODO Meaningless statement? - + public MatchesAccess(Connection c){ + connection = c; - + System.out.println("GOING TO TRY CONNECTION STATEMENT"); try { statement = connection.createStatement(); } catch (SQLException e) { @@ -42,7 +46,7 @@ public MatchesAccess(MathGame game, Connection c){ public void reconnectStatement() { try { - connection = mathGame.getMySQLAccess().getConnection(); + connection = MathGame.getMySQLAccess().getConnection(); statement = connection.createStatement(); System.out.println("REDO STATEMENT SUCCESS"); } catch (SQLException e) { @@ -52,18 +56,18 @@ public void reconnectStatement() { /** * Hosts a new game - * @return The match number of the game (given by the database) + * @return The match number ID(?) of the new game (from the database) */ public int hostGame() { try { statement.executeUpdate("INSERT INTO sofiav_mathgame.matches "+ "(Player1, Type, Difficulty, Scoring, NumPlayers, Rounds)" + - " VALUES ('" + mathGame.getUser().getName() + "', '" + mathGame.getGameManager().getGame().getType() + - "', '" + mathGame.getGameManager().getGame().getDiff() + "', '" + mathGame.getGameManager().getGame().getScoring() + "', '" + - mathGame.getGameManager().getGame().getNumberOfPlayers() + "', '"+ mathGame.getGameManager().getGame().getRounds() + "')" ); + " VALUES ('" + MathGame.getUser().getName() + "', '" + MathGame.getGameManager().getGame().getType() + + "', '" + MathGame.getGameManager().getGame().getDiff() + "', '" + MathGame.getGameManager().getGame().getScoring() + "', '" + + MathGame.getGameManager().getGame().getNumberOfPlayers() + "', '"+ MathGame.getGameManager().getGame().getRounds() + "')" ); System.out.println("Created online game"); - ResultSet resultSet = statement.executeQuery("select * from sofiav_mathgame.matches where sofiav_mathgame.matches.Player1='" + mathGame.getUser().getName() + "'"); + ResultSet resultSet = statement.executeQuery("select * from sofiav_mathgame.matches where sofiav_mathgame.matches.Player1='" + MathGame.getUser().getName() + "'"); resultSet.next(); matchNum = resultSet.getInt("ID"); @@ -93,16 +97,28 @@ public ArrayList getCurrentGames() { gamesList.add(new Game(resultSet.getInt("ID"), numPlayers, playerNames, resultSet.getString("Type"), resultSet.getString("Scoring"), resultSet.getString("Difficulty"), resultSet.getInt("Rounds"))); } } catch (SQLException e) { - e.printStackTrace(); + if(e.getSQLState().equals("08S01") || e.getSQLState().equals("08003")) + { + MathGame.dbConnected = false; + System.err.println("DB fail in getCurrentGames()"); + if(MathGame.getMySQLAccess().displayUserConnectAgain() == true) + { + GameManager.getMatchesAccess().reconnectStatement(); + } + return null; + } + else + e.printStackTrace(); } return gamesList; } /** - * Joins a game (of the given gameID) that is being hosted + * Join the specified game that is being hosted + * @param gameID - The ID of the game to be joined */ - public void joinGame (int gameID) { + public void joinGame(int gameID) { try { statement = connection.createStatement(); } catch (SQLException e) { @@ -111,7 +127,7 @@ public void joinGame (int gameID) { try { statement.executeUpdate("Update sofiav_mathgame.matches " + - "set Player2=" + " '"+mathGame.getUser().getName() + "' " + + "set Player2=" + " '"+MathGame.getUser().getName() + "' " + "where sofiav_mathgame.matches.ID=" + gameID); } catch (SQLException e) { e.printStackTrace(); @@ -142,7 +158,14 @@ public ArrayList getScores() { System.out.println("score"+i+ ":" + score); } } catch (SQLException e) { - e.printStackTrace(); + if(e.getSQLState().equals("08S01")) + { + MathGame.dbConnected = false; + MathGame.getMySQLAccess().displayUserConnectAgain(); + } + else + e.printStackTrace(); + } return scores; @@ -150,23 +173,34 @@ public ArrayList getScores() { /** * Update the score of the match + * @param score - The round score to add */ - public void updateScore (int score) { + public void updateScore(int score) { try { statement = connection.createStatement(); } catch (SQLException e) { - e.printStackTrace(); + System.out.println("state: " + e.getSQLState()); + + if(e.getSQLState().equals("08003")) + { + MathGame.dbConnected = false; + //If the reconnect doesn't work, exit the function + if(!MathGame.getMySQLAccess().displayUserConnectAgain()) + return; + } + else + e.printStackTrace(); } try { - System.out.println("this id " + mathGame.getUser().getPlayerID()); - int currentScore = getScores().get(mathGame.getUser().getPlayerID()-1); + System.out.println("this id " + MathGame.getUser().getPlayerID()); + int currentScore = getScores().get(MathGame.getUser().getPlayerID()-1); System.out.println("Current score from db: " + currentScore); int newScore = currentScore + score; System.out.println("round score: " + score + "---New total score: " + newScore); statement.executeUpdate("Update sofiav_mathgame.matches " + - "set Player"+mathGame.getUser().getPlayerID() + "Score=" + + "set Player"+MathGame.getUser().getPlayerID() + "Score=" + " '"+ newScore + "' " + "where sofiav_mathgame.matches.ID=" + matchNum); @@ -188,16 +222,18 @@ public void removeGame() { } /** - * Checks whether the game is full (yet); if so, start the game - * @return Whether the game is full (true) or not + * Checks whether the game is full (yet) and should be started + * @return True if the game is full */ public boolean checkForFullGame() { try { ResultSet resultSet = statement.executeQuery("select * from sofiav_mathgame.matches where ID=" + matchNum); resultSet.next(); + System.out.println(resultSet + " hello"); if(!resultSet.getString("Player2").equals("")) { System.out.println("Game is now full and can start"); + JOptionPane.showMessageDialog(null, "Full"); return true; } /* @@ -221,7 +257,23 @@ public void finished() { worker.start(); */ } catch (SQLException e) { - e.printStackTrace(); + if(e.getSQLState().equals("08S01") || e.getSQLState().equals("08003")) + { + System.out.println("Error in checking for full game"); + MathGame.dbConnected = false; + //HostMenu.waitForPlayer.stop(); + HostMenu.waitForPlayer.interrupt(); + System.out.println("Cnct?2 :" + MathGame.dbConnected); + + System.out.println("Going to show multimenu"); + MathGame.showMenu(MathGame.Menu.MULTIMENU); + System.out.println("Cnct?3 :" + MathGame.dbConnected); + + ((MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU))).refreshDatabase(); + ((MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU))).refreshTimer.start(); + } + else + e.printStackTrace(); } return false; @@ -229,7 +281,7 @@ public void finished() { /** * Checks whether both players' scores have been updated - * @return Whether the scores have been updated (true) or not + * @return True if the scores have been updated */ public boolean checkForPlayersScoresUpdated(int currentScore1, int currentScore2) { try { @@ -322,8 +374,8 @@ public void incrementRound() { /** * @param matchID - Match number - * @param playerID - The id of the player you want (player1, player2....) - * @return name of the player + * @param playerID - The ID of the player you want (player1, player2....) + * @return The name of the player (or "DB Fail" if an exception occurs) */ public String getPlayerName(int matchID, int playerID){ try { @@ -332,7 +384,7 @@ public String getPlayerName(int matchID, int playerID){ return resultSet.getString("Player"+playerID); } catch(SQLException e){ e.printStackTrace(); + return "DB Fail"; } - return "DB Fail"; } } \ No newline at end of file diff --git a/src/com/mathgame/database/MySQLAccess.java b/src/com/mathgame/database/MySQLAccess.java index b2ef64d..968cb37 100644 --- a/src/com/mathgame/database/MySQLAccess.java +++ b/src/com/mathgame/database/MySQLAccess.java @@ -7,8 +7,16 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; +import java.util.Random; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.MathGame; +import com.mathgame.math.MathGame.Menu; +import com.mathgame.math.TypeManager.GameType; +import com.mathgame.network.GameManager; /** * The MySQLAccess class handles connections to the MySQL database @@ -22,7 +30,7 @@ public class MySQLAccess{ private final String user = "sofiav_user"; // "egarciao@localhost"; private final String pass = "Mathgames1"; //"oL20wC06xd"; - private Connection connection = null; + protected Connection connection = null; private Statement statement = null; private PreparedStatement preparedStatement = null; private ResultSet resultSet = null; @@ -40,7 +48,7 @@ public class MySQLAccess{ public MySQLAccess(MathGame game) { mathGame = game; - gameAccess = new GameAccess(game, connection); + gameAccess = new GameAccess(connection); System.out.println("11111111111" + game.getBackground()); //TODO Just a test message? It often returns "null" anyway } @@ -75,6 +83,7 @@ public boolean connect() { System.out.println("ErrorO: " + e.getMessage()); System.out.println("Error1: " + e.getClass().getName()); sqlError = e.getMessage(); + // sqlError.concat(e.getCause().toString()); // sqlError = e.getStackTrace().toString(); } @@ -111,7 +120,7 @@ public String getOp() /** * @return The string value of num2 (the righthand NumberCard) */ - public String getNum2() + public String getNum2() { // System.out.println("num2 " + num2); return num2; @@ -132,15 +141,29 @@ public String getAnswer() */ public void getVals() throws Exception { + //TODO a better implementation would be to simply pass the type into the getvals method rather than find it here. String gameType; - if (mathGame != null) { - gameType = mathGame.getTypeManager().getType().toString().toLowerCase(); + //select the type table (that is a member of the types selected by user) + Random gen = new Random(); + int rand = gen.nextInt(5); + while(!MathGame.getTypeManager().getType().contains(GameType.values()[rand])) + rand = gen.nextInt(5); + gameType = GameType.values()[rand].gameTypeString.toLowerCase(); + + /*if (mathGame != null) { + gameType = MathGame.getTypeManager().getType().toString().toLowerCase(); } else { gameType = "integers"; - } + }*/ try { statement = connection.createStatement(); + /*if(gameType.equals(GameType.MIXED.gameTypeString.toLowerCase())) { + //mixed, just select one table + Random gen = new Random(); + resultSet = statement.executeQuery("select * from sofiav_mathgame." + GameType.values()[gen.nextInt(5)].gameTypeString.toLowerCase()); + } + else*/ resultSet = statement.executeQuery("select * from sofiav_mathgame." + gameType); int offset = (int)((Math.random()*98) + 1); @@ -163,6 +186,7 @@ public void getVals() throws Exception */ } catch (Exception e) { System.out.println("SQLException: " + e.getMessage()); + throw e; } /* @@ -172,56 +196,6 @@ public void getVals() throws Exception */ } - /** - * Test function for writing and reading comments to and from the database? - * @throws Exception - */ - public void writeCommentsDatabase() throws Exception { - try { - // Class.forName("com.mysql.jdbc.Driver"); - // connect = DriverManager.getConnection("jdbc:MySQL://localhost/test", "root", ""); - - statement = connection.createStatement(); - System.out.println("here1"); - resultSet = statement.executeQuery("select * from test.comments"); - writeResultSet(resultSet); - - preparedStatement = connection.prepareStatement("INSERT INTO test.comments values(default, ?, ?, ?, ?, ?, ?)"); - // Columns in test.comments - // myuser, email, webpage, datum, summary, COMMENTS - preparedStatement.setString(1, "Test"); - preparedStatement.setString(2, "TestEmail"); - preparedStatement.setString(3, "TestWebpage"); - preparedStatement.setDate(4, java.sql.Date.valueOf("2009-12-11")); - - preparedStatement.setString(5, "Test Summary"); - preparedStatement.setString(6, "Test Comment"); - System.out.println("here2"); - preparedStatement.executeUpdate(); - - preparedStatement = connection.prepareStatement("SELECT myuser, webpage, datum, summary, comments FROM test.comments"); - System.out.println("here3"); - resultSet = preparedStatement.executeQuery(); - writeResultSet(resultSet); - - /* - preparedStatement = connect.prepareStatement("DELETE FROM test.comments WHERE myuser=?;"); - preparedStatement.setString(1, "Test"); - preparedStatement.executeUpdate(); - */ - - resultSet = statement.executeQuery("SELECT * FROM test.comments;"); - System.out.println("Writing meta data"); - writeMetaData(resultSet); - } catch (Exception e) { - throw e; - } finally { - close(); - System.out.println("ALMOST"); - } - System.out.println("AT THE END"); - } - /** * Prints out all meta data from the given ResultSet * @param resultSet - The current ResultSet being used @@ -314,7 +288,7 @@ public void close() { * @throws Exception */ public ArrayList getUsersGame() throws Exception { - gameAccess = new GameAccess(mathGame, connection); + gameAccess = new GameAccess(connection); return gameAccess.getUsers(); } @@ -322,19 +296,65 @@ public ArrayList getUsersGame() throws Exception { * Adds the user to the list */ public void addUser() { - gameAccess.addUser(); + gameAccess.addOnlineUser(); } /** * Removes the user from the list */ public void removeUser() { - gameAccess.removeUser(connection); + gameAccess.removeOnlineUser(connection); + } + + public boolean loginUser(String u, char[] p){ + return gameAccess.checkUserLogin(u, p); } - /* - public boolean isConnected() { - return connect; + public void registerUser(String u, String p){ + gameAccess.registerUser(u, p); + } + + public boolean displayUserConnectAgain(){ + Object[] options = {"Yes", "No"}; + int option = JOptionPane.showOptionDialog(new JPanel(), + "Could not connect to server - Connect again?", + "Connect again?", + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, + options, + null); + if(option == 0)//Yes - try to connect again + { + if (!MathGame.getMySQLAccess().connect()) { + System.out.println("COULD NOT CONNECT"); + GameDialogFactory.showGameMessageDialog(new JPanel(), "Connect fail", "Could not connect-" + + "Check your internet connection", GameDialogFactory.OK); + System.out.println("Could not connect to network"); + MathGame.getTypeManager().setOffline(true); + MathGame.showMenu(Menu.MAINMENU); + return false; + } + else { + System.out.println("CONNECTED ONCE AGAIN"); + GameDialogFactory.showGameMessageDialog(new JPanel(), "Success", "Connected!", GameDialogFactory.OK); + if(GameManager.getMatchesAccess() != null) + GameManager.getMatchesAccess().reconnectStatement(); + else + { + GameManager gm = new GameManager(); + GameManager.getMatchesAccess().reconnectStatement(); + } + MathGame.dbConnected = true; + MathGame.getTypeManager().setOffline(false); + return true; + } + } + else {//user declines to connect again; so initiate offline mode + MathGame.getTypeManager().setOffline(true); + MathGame.showMenu(Menu.MAINMENU); + } + return false; + } - */ } diff --git a/src/com/mathgame/database/Values.java b/src/com/mathgame/database/Values.java deleted file mode 100644 index 8ceea73..0000000 --- a/src/com/mathgame/database/Values.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.mathgame.database; - -import java.io.*; - -/** - * This is merely a class for database testing; do not run from here! - * @author Hima - */ -public class Values { - - public static void main(String[] args) { - int num1 = 0; - String op = ""; - int num2 = 0; - - FileWriter fstream; - BufferedWriter out = null; - String[] ops = {"+", "-", "*", "/"}; - - try { - fstream = new FileWriter("out.txt"); - out = new BufferedWriter(fstream); - } catch(Exception e) { - System.err.println(e.getMessage()); - } - - MySQLAccess gen = new MySQLAccess(); - - - for (int i = 0; i < 100; i++) { - num1 = (int)(Math.random()*20); - num2 = (int)(Math.random()*20); - op = ops[(int)(Math.random()*4)]; - - if (num2 == 0 && op.equals("/")) { - continue; - } - Double answer = gen.calc(num1, op, num2); - - try { - out.write(num1 + "\t" + op + "\t" + num2 + "\t" + answer + "\r\n"); - - System.out.println(num1); - System.out.println(op); - System.out.println(num2); - System.out.println(answer + "\n"); - } catch (Exception e) { - System.err.println("Error: " + e.getMessage()); - } - } - - try { - out.close(); - } catch (Exception e) { - System.err.println(e.getMessage()); - } - - System.out.println("Finished"); - - // System.err.println("Test err"); - } -} \ No newline at end of file diff --git a/src/com/mathgame/guicomponents/GameButton.java b/src/com/mathgame/guicomponents/GameButton.java new file mode 100644 index 0000000..e72edef --- /dev/null +++ b/src/com/mathgame/guicomponents/GameButton.java @@ -0,0 +1,81 @@ +/** + * + */ +package com.mathgame.guicomponents; + +import java.awt.Dimension; +import java.awt.Font; + +import javax.swing.ImageIcon; +import javax.swing.JButton; + +import com.mathgame.math.MathGame; + +/** + * The GameButton class holds information to create a standard game button + * @author Roland + */ +public class GameButton extends JButton { + + private static final long serialVersionUID = 8003043712181506594L; + + private static final String BG_FILE = "/images/DefaultButtonImage1.png"; + private static final String ROLLOVER_IMAGE_FILE = "/images/DefaultButtonImage2.png"; + private static final String PRESSED_IMAGE_FILE = "/images/DefaultButtonImage3.png"; + + private static final int DEFAULT_WIDTH = 130; + private static final int DEFAULT_HEIGHT = 30; + + private static Font DEFAULT_FONT = MathGame.eurostile20; + + private static ImageIcon backgroundImage = new ImageIcon(GameButton.class.getResource(BG_FILE)); + private static ImageIcon rollOverImage = new ImageIcon(GameButton.class.getResource(ROLLOVER_IMAGE_FILE)); + private static ImageIcon pressedImage = new ImageIcon(GameButton.class.getResource(PRESSED_IMAGE_FILE)); + + private Dimension size; + + public GameButton(String title, Dimension size) { + super(title); + this.size = size; + initButton(); + } + + public GameButton(String title) { + super(title); + size = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); + initButton(); + } + + public GameButton() { + super(); + size = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); + initButton(); + } + + /** + * Sets the button specifications + */ + private void initButton() { + setSize(size); + setFont(DEFAULT_FONT); + setHorizontalTextPosition(JButton.CENTER); + setVerticalTextPosition(JButton.CENTER); + setBorderPainted(false); + setContentAreaFilled(false); + setImages(); + } + + /** + * Tries to set the images for the button (as part of initialization) + */ + private void setImages() { + try { + setIcon(backgroundImage); + setRolloverIcon(rollOverImage); + setPressedIcon(pressedImage); + } catch(Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/src/com/mathgame/guicomponents/GameDialogFactory.java b/src/com/mathgame/guicomponents/GameDialogFactory.java new file mode 100644 index 0000000..55f209b --- /dev/null +++ b/src/com/mathgame/guicomponents/GameDialogFactory.java @@ -0,0 +1,158 @@ +/** + * + */ +package com.mathgame.guicomponents; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import com.mathgame.math.MathGame; + +/** + * Creates dialog boxes with a look and feel consistent with rest of game + * @author Roland + * + */ +public class GameDialogFactory { + + public static final int OK = 0; + public static final int OK_CANCEL = 1; + + private static GameDialog diag; + + private static int choice; + + /** + * Creates a customized messagebox + * @param parent + * @param title to go on titlebar + * @param message the contents of the dialog box + * @param type include ok button or cancel button + */ + public static void showGameMessageDialog(Component parent, String title, String message, int type) { + JPanel contents = new JPanel(); + contents.setLayout(new BoxLayout(contents, BoxLayout.PAGE_AXIS)); + contents.setBackground(MathGame.offWhite); + ((JPanel)contents).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + JLabel mLabel = new JLabel(message); + mLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + mLabel.setFont(MathGame.eurostile20); + contents.add(mLabel); + contents.add(Box.createRigidArea(new Dimension(0, 10))); + + diag = new GameDialogFactory().new GameDialog(title, contents); + + switch(type) { + case OK_CANCEL: + GameButton cancel = new GameButton("Cancel"); + cancel.setAlignmentX(Component.CENTER_ALIGNMENT); + cancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + diag.dispose(); + } + }); + contents.add(cancel); + case OK: + GameButton ok = new GameButton("Ok"); + ok.setAlignmentX(Component.CENTER_ALIGNMENT); + ok.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.out.println("diag: " + diag); + diag.dispose(); + } + }); + contents.add(ok); + break; + } + + diag.pack(); + diag.setVisible(true); + } + + public static int showGameOptionDialog(Component parent, String title, String message) { + + JPanel contents = new JPanel(); + contents.setLayout(new BoxLayout(contents, BoxLayout.PAGE_AXIS)); + contents.setBackground(MathGame.offWhite); + ((JPanel)contents).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + JLabel mLabel = new JLabel(message); + mLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + mLabel.setFont(MathGame.eurostile20); + contents.add(mLabel); + contents.add(Box.createRigidArea(new Dimension(0, 10))); + + diag = new GameDialogFactory().new GameDialog(title, contents); + + GameButton yes = new GameButton("Yes"); + yes.setAlignmentX(Component.CENTER_ALIGNMENT); + yes.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + choice = 0; + diag.setVisible(false); + } + }); + contents.add(yes); + + GameButton no = new GameButton("No"); + no.setAlignmentX(Component.CENTER_ALIGNMENT); + no.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + choice = 1; + diag.setVisible(false); + } + }); + contents.add(no); + + diag.pack(); + diag.setVisible(true); + return choice; + } + + public class GameDialog extends JDialog { + private Container contents; + + /** + * Clones an existing JDialog and applies GameDialog specifications + * @param clone + */ + public GameDialog(JDialog clone) { + contents = clone.getContentPane(); + contents.setBackground(MathGame.offWhite); + } + + /** + * Constructs JDialog with a prespecified content panel. Must be manually set visible and packed + * @param title on titlebar + * @param contents + */ + public GameDialog(String title, Container contents) { + super((JFrame)MathGame.getWorkspacePanel().getTopLevelAncestor(), true);//uses the JFrame + setTitle(title); + this.contents = contents; + setContentPane(contents); + setLocationRelativeTo(null);//centers dialog on screen + setAutoRequestFocus(true);//puts dialog on top (focused) + } + + /** + * @return the contents + */ + public Container getContents() { + return contents; + } + + } +} diff --git a/src/com/mathgame/math/Calculate.java b/src/com/mathgame/math/Calculate.java index e0e7e73..e6bc32f 100644 --- a/src/com/mathgame/math/Calculate.java +++ b/src/com/mathgame/math/Calculate.java @@ -17,10 +17,9 @@ public class Calculate { * @param c1 - The number card on the left * @param oper - The card that contains the operation * @param c2 - The number card on the right - * @param game - The MathGame object * @return The value of the given expression */ - public static Double calculate(Component c1, Component oper, Component c2, MathGame game) { + public static Double calculate(Component c1, Component oper, Component c2) { NumberCard card1 = null; NumberCard card2 = null; OperationCard operation = null; @@ -33,8 +32,8 @@ public static Double calculate(Component c1, Component oper, Component c2, MathG return null; } - double num1 = NumberCard.parseNumFromText(card1.getValue()); - double num2 = NumberCard.parseNumFromText(card2.getValue()); + double num1 = card1.getValue(); + double num2 = card2.getValue(); System.out.println("num1 final : " + card1.getValue()); System.out.println("num2 final : " + num2); System.out.println("op final: " + operation.getOperation()); @@ -49,6 +48,8 @@ public static Double calculate(Component c1, Component oper, Component c2, MathG answer = num1 * num2; } else if(op == "divide") { answer = num1 / num2; + } else if(op == "exponent") { + answer = Math.pow(num1, num2); } else { answer = -1; } diff --git a/src/com/mathgame/math/CompMover.java b/src/com/mathgame/math/CompMover.java index a2b2cce..987691e 100644 --- a/src/com/mathgame/math/CompMover.java +++ b/src/com/mathgame/math/CompMover.java @@ -6,10 +6,12 @@ import java.awt.event.MouseEvent; import javax.swing.JLabel; +import javax.swing.SwingUtilities; import javax.swing.event.MouseInputAdapter; import com.mathgame.cards.NumberCard; import com.mathgame.cards.OperationCard; +import com.mathgame.panels.CardPanel; /** * The CompMover class is the adapter class used for moving components such as the JLabels around on @@ -17,10 +19,10 @@ * use, set the component's add mouseListener and mouseMotionListener parameters * to the object which has been created from this class. *

- * For example: - * CompMover mover = new CompMover(MathGame.this); - * jlabel.addMouseListener(mover); - * jlabel.addMouseMotionListener(mover); + * For example:
+ * CompMover mover = new CompMover();
+ * item.addMouseListener(mover);
+ * item.addMouseMotionListener(mover);
*

* Note: This class should only be instantiated in the MathGame class */ @@ -30,30 +32,18 @@ public class CompMover extends MouseInputAdapter { boolean draggingCard; boolean moved; - static MathGame mathGame; // Components from the main class - - JLabel[] cards = new JLabel[11]; // card1, card2..opA,S... - Rectangle[] cardHomes = new Rectangle[11]; // home1, home2...opA,S... - + JLabel[] cards = new JLabel[12]; // card1, card2..opA,S... + Rectangle[] cardHomes = new Rectangle[12]; // home1, home2...opA,S... + /** * The constructor (which should only be called in the MathGame class) - * @param mathGame - The MathGame object (It is recommended to pass "MathGame.this" as an argument) */ - public CompMover(MathGame mathGame) { + public CompMover() { draggingCard = false; moved = false; - CompMover.mathGame = mathGame; - - cards = mathGame.getCards(); - cardHomes = mathGame.getCardHomes(); - } - /** - * Initializes an instance of CompMover (without passing in a MathGame object) - */ - public CompMover() { - draggingCard = false; - // setViews(); + cards = MathGame.getCards(); + cardHomes = MathGame.getCardHomes(); } /** @@ -61,21 +51,31 @@ public CompMover() { */ @Override public void mousePressed(MouseEvent e) { - + System.out.println("mouse pressed event"); selectedComponent = (Component) (e.getSource()); - // System.out.println(selectedComponent.getParent()); + //System.out.println("parent: " + selectedComponent.getParent()); // Point tempPoint = selectedComponent.getLocation(); offset = e.getPoint(); + Point realLoc = e.getLocationOnScreen(); + + System.out.println("location on screen: " + realLoc); + + Rectangle r = selectedComponent.getBounds(); + System.out.println("original bounds: " + r); + + draggingCard = true; try { - if (selectedComponent.getParent().equals(mathGame.getWorkspacePanel())) { - - mathGame.getWorkspacePanel().remove(selectedComponent); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getMasterPane().add(selectedComponent, new Integer(1)); - mathGame.getMasterPane().revalidate(); - mathGame.getMasterPane().repaint(); + if (selectedComponent.getParent().equals(MathGame.getWorkspacePanel())) { + r = SwingUtilities.convertRectangle(MathGame.getWorkspacePanel(), r, MathGame.getMasterPane()); + System.out.println("new bounds: " + r); + + MathGame.getWorkspacePanel().remove(selectedComponent); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getMasterPane().add(selectedComponent, new Integer(1)); + MathGame.getMasterPane().revalidate(); + MathGame.getMasterPane().repaint(); // offset = selectedComponent.getLocationOnScreen(); // selectedComponent.setBounds(MouseInfo.getPointerInfo().getLocation().x, @@ -89,21 +89,30 @@ public void mousePressed(MouseEvent e) { System.out.println(selectedComponent.getLocationOnScreen()); System.out.println(tempPoint); */ - selectedComponent.setLocation(-200, -200); + + //selectedComponent.setLocation(300, 400); + //selectedComponent.setLocation(realLoc.x, realLoc.y); + //selectedComponent.setLocation(offset.x, offset.y); + selectedComponent.setBounds(r); // selectedComponent.setSize(cardHomes[1].getSize().width, // cardHomes[1].getSize().height); - } else if (selectedComponent.getParent().equals(mathGame.getHoldPanel())) { + } else if (selectedComponent.getParent().equals(MathGame.getHoldPanel())) { + r = SwingUtilities.convertRectangle(MathGame.getHoldPanel(), r, MathGame.getMasterPane()); + System.out.println("new bounds: " + r); + + int tempX = selectedComponent.getX(); int tempY = selectedComponent.getLocationOnScreen().y; - mathGame.getHoldPanel().remove(selectedComponent); - mathGame.getHoldPanel().revalidate(); - mathGame.getMasterPane().add(selectedComponent, new Integer(1)); - mathGame.getMasterPane().revalidate(); - mathGame.getMasterPane().repaint(); + MathGame.getHoldPanel().remove(selectedComponent); + MathGame.getHoldPanel().revalidate(); + MathGame.getMasterPane().add(selectedComponent, new Integer(1)); + MathGame.getMasterPane().revalidate(); + MathGame.getMasterPane().repaint(); - selectedComponent.setLocation(tempX, tempY); + //selectedComponent.setLocation(tempX, tempY); + selectedComponent.setBounds(r); } /* else { System.out.println("normal workpanel:"+workPanel); @@ -122,6 +131,7 @@ public void mousePressed(MouseEvent e) { */ @Override public void mouseReleased(MouseEvent e) { + System.out.println("mouse released event"); draggingCard = false; Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(); @@ -131,8 +141,8 @@ public void mouseReleased(MouseEvent e) { selectedComponent.getWidth(), selectedComponent.getHeight()); try { - box2.setBounds(mathGame.getWorkspacePanel().getBounds()); - box3.setBounds(mathGame.getHoldPanel().getBounds()); + box2.setBounds(MathGame.getWorkspacePanel().getBounds()); + box3.setBounds(MathGame.getHoldPanel().getBounds()); } catch (Exception ex) { System.out.println("Bounds could not be set"); } @@ -143,67 +153,60 @@ public void mouseReleased(MouseEvent e) { NumberCard temp = (NumberCard)selectedComponent; if (temp.getHome() == "home") { // Meaning the card originated from cardPanel - if (temp.getNumberTag() == mathGame.getCardPanel().card1.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(0, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card2.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(1, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card3.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(2, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card4.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(3, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card5.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(4, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card6.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(5, false); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + if(temp.getNumberTag() == MathGame.getCardPanel().getCards()[i].getNumberTag()){ + MathGame.getCardPanel().changeCardExistence(i, false); + break; + } } } - if (mathGame.getWorkspacePanel().getComponentCount() == 1 && - mathGame.getWorkspacePanel().getComponent(0) instanceof OperationCard) { + if (MathGame.getWorkspacePanel().getComponentCount() == 1 && + MathGame.getWorkspacePanel().getComponent(0) instanceof OperationCard) { // Force card to be placed BEFORE operator - OperationCard tempOpCard = (OperationCard)(mathGame.getWorkspacePanel().getComponent(0)); - mathGame.getWorkspacePanel().remove(0); // Temporarily take out operation card - mathGame.getMasterPane().remove(selectedComponent); - mathGame.getMasterPane().revalidate(); - mathGame.getWorkspacePanel().add(selectedComponent);// Put numbercard - mathGame.getWorkspacePanel().add(tempOpCard);// Put back operation AFTER numbercard - mathGame.getWorkspacePanel().revalidate(); - mathGame.getMasterPane().repaint(); + OperationCard tempOpCard = (OperationCard)(MathGame.getWorkspacePanel().getComponent(0)); + MathGame.getWorkspacePanel().remove(0); // Temporarily take out operation card + MathGame.getMasterPane().remove(selectedComponent); + MathGame.getMasterPane().revalidate(); + MathGame.getWorkspacePanel().add(selectedComponent);// Put numbercard + MathGame.getWorkspacePanel().add(tempOpCard);// Put back operation AFTER numbercard + MathGame.getWorkspacePanel().revalidate(); + MathGame.getMasterPane().repaint(); } else { - mathGame.getMasterPane().remove(selectedComponent); - mathGame.getMasterPane().revalidate(); - mathGame.getWorkspacePanel().add(selectedComponent); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getMasterPane().repaint(); + MathGame.getMasterPane().remove(selectedComponent); + MathGame.getMasterPane().revalidate(); + MathGame.getWorkspacePanel().add(selectedComponent); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getMasterPane().repaint(); } } else if (selectedComponent instanceof OperationCard) { // Now attempt to put an operation card in between if necessary - if (mathGame.getWorkspacePanel().getComponentCount() == 0) { + if (MathGame.getWorkspacePanel().getComponentCount() == 0) { // Nothing in work panel; do not put operation restoreCard(); - } else if (mathGame.getWorkspacePanel().getComponentCount() == 1) { + } else if (MathGame.getWorkspacePanel().getComponentCount() == 1) { // There is presumably one NumberCard in there - mathGame.getMasterPane().remove(selectedComponent); - mathGame.getMasterPane().revalidate(); - mathGame.getWorkspacePanel().add(selectedComponent); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getMasterPane().repaint(); - } else if (mathGame.getWorkspacePanel().getComponentCount() == 2) { + MathGame.getMasterPane().remove(selectedComponent); + MathGame.getMasterPane().revalidate(); + MathGame.getWorkspacePanel().add(selectedComponent); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getMasterPane().repaint(); + } else if (MathGame.getWorkspacePanel().getComponentCount() == 2) { // Check if its two NumberCards or a NumberCard & OperationCard - if (mathGame.getWorkspacePanel().getComponent(0) instanceof NumberCard - && mathGame.getWorkspacePanel().getComponent(1) instanceof NumberCard) { + if (MathGame.getWorkspacePanel().getComponent(0) instanceof NumberCard + && MathGame.getWorkspacePanel().getComponent(1) instanceof NumberCard) { OperationCard temp = (OperationCard) selectedComponent; - mathGame.getMasterPane().remove(selectedComponent); - mathGame.getMasterPane().revalidate(); - NumberCard tempNumCard = (NumberCard)(mathGame.getWorkspacePanel().getComponent(1)); - mathGame.getWorkspacePanel().remove(1); // Remove the second number card; - mathGame.getWorkspacePanel().revalidate(); - mathGame.getWorkspacePanel().add(temp); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getWorkspacePanel().add(tempNumCard); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getMasterPane().repaint(); + MathGame.getMasterPane().remove(selectedComponent); + MathGame.getMasterPane().revalidate(); + NumberCard tempNumCard = (NumberCard)(MathGame.getWorkspacePanel().getComponent(1)); + MathGame.getWorkspacePanel().remove(1); // Remove the second number card; + MathGame.getWorkspacePanel().revalidate(); + MathGame.getWorkspacePanel().add(temp); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getWorkspacePanel().add(tempNumCard); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getMasterPane().repaint(); } else { restoreCard(); } @@ -220,25 +223,18 @@ public void mouseReleased(MouseEvent e) { NumberCard temp = (NumberCard) selectedComponent; if (temp.getHome() == "home") { // Meaning it originated from cardPanel - if (temp.getNumberTag() == mathGame.getCardPanel().card1.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(0, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card2.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(1, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card3.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(2, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card4.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(3, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card5.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(4, false); - } else if (temp.getNumberTag() == mathGame.getCardPanel().card6.getNumberTag()) { - mathGame.getCardPanel().changeCardExistence(5, false); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + if(temp.getNumberTag() == MathGame.getCardPanel().getCards()[i].getNumberTag()){ + MathGame.getCardPanel().changeCardExistence(i, false); + break; + } } } - mathGame.getMasterPane().remove(selectedComponent); - mathGame.getMasterPane().revalidate(); - mathGame.getHoldPanel().add(selectedComponent); - mathGame.getHoldPanel().revalidate(); - mathGame.getMasterPane().repaint(); + MathGame.getMasterPane().remove(selectedComponent); + MathGame.getMasterPane().revalidate(); + MathGame.getHoldPanel().add(selectedComponent); + MathGame.getHoldPanel().revalidate(); + MathGame.getMasterPane().repaint(); } else if (selectedComponent instanceof OperationCard) { // Don't put operations card in hold restoreCard(); @@ -249,11 +245,11 @@ public void mouseReleased(MouseEvent e) { restoreCard(); try { if (selectedComponent.getName().equals(("Answer"))) { - mathGame.getMasterPane().remove(selectedComponent); - mathGame.getMasterPane().revalidate(); - mathGame.getHoldPanel().add(selectedComponent); - mathGame.getHoldPanel().revalidate(); - mathGame.getMasterPane().repaint(); + MathGame.getMasterPane().remove(selectedComponent); + MathGame.getMasterPane().revalidate(); + MathGame.getHoldPanel().add(selectedComponent); + MathGame.getHoldPanel().revalidate(); + MathGame.getMasterPane().repaint(); } } catch (Exception ex) { System.err.println("selectedComponent is unnamed"); @@ -280,6 +276,7 @@ private void restoreCard() { */ @Override public void mouseDragged(MouseEvent e) { + //System.out.println("mouse dragged event"); // System.out.println(e.getLocationOnScreen()); if (draggingCard) { Rectangle r = selectedComponent.getBounds(); diff --git a/src/com/mathgame/math/MathGame.java b/src/com/mathgame/math/MathGame.java index 1b70eb3..64129c5 100644 --- a/src/com/mathgame/math/MathGame.java +++ b/src/com/mathgame/math/MathGame.java @@ -3,32 +3,41 @@ import javax.swing.*; import com.mathgame.database.*; +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.menus.*; import com.mathgame.network.*; import com.mathgame.panels.*; - import java.awt.*; import java.awt.dnd.DropTarget; -import java.awt.event.*; import java.util.concurrent.ExecutionException; /** * The main class of the program */ -public class MathGame extends Container implements ActionListener { +public class MathGame extends Container { private static final long serialVersionUID = 412526093812019078L; - int appWidth = 900; // 1300 or 900 - int appHeight = 620; - public static final double epsilon = 0.000000000001; // 10^-12, equivalent to TI-84 precision - public static final String operations[] = {"+", "-", "*", "/"}; + //Global Variables (Public) + public static final double epsilon = 0.000000000001; // 10^-10 + public static final String[] operations = {"+", "-", "*", "/"}; + public static final String[] scorings = {"Complexity", "Speed", "Mix"}; // Mixed scoring is a combination of speed and complexity + + public static final Font eurostile36 = new Font("Impact", Font.PLAIN, 36); + public static final Font eurostile24 = new Font("Impact", Font.PLAIN, 24); + public static final Font eurostile20 = new Font("Impact", Font.PLAIN, 20); + public static final Font eurostile16 = new Font("Impact", Font.PLAIN, 16); - - private MainMenu mainMenu; - private MultiMenu multiMenu; - private OptionMenu optionMenu; - private HostMenu hostMenu; + public static final Color offWhite = new Color(255, 255, 204); + + private static final Dimension size = new Dimension(900, 620); + + //Menus + private static LoginMenu loginMenu; + private static RegisterMenu registerMenu; + private static MainMenu mainMenu; + private static MultiMenu multiMenu; + private static HostMenu hostMenu; /** * The Menu enumeration is used for selecting which menu to use @@ -40,24 +49,29 @@ public static enum Menu { GAME ("CardLayoutPanel Game"), /** - * The main (starting) menu + * The login menu */ - MAINMENU ("CardLayoutPanel MainMenu"), + LOGIN ("CardLayoutPanel LoginMenu"), /** - * The multiplayer menu + * The registration menu */ - MULTIMENU ("CardLayoutPanel Multiplayer"), + REGISTER ("CardLayoutPanel RegisterMenu"), + + /** + * The main menu + */ + MAINMENU ("CardLayoutPanel MainMenu"), /** - * The game options (aka setup) menu + * The multiplayer menu */ - OPTIONMENU ("CardLayoutPanel OptionMenu"), + MULTIMENU ("CardLayoutPanel Multiplayer"), /** * The menu for hosting new games */ - HOSTMENU ("CardLayoutPanel HostMenu"); + HOSTMENU ("CardLayoutPanel HostMenu"); public final String cardLayoutString; Menu(String cardLayoutString) { @@ -79,60 +93,74 @@ public static enum GameState { */ COMPETITIVE }; - private GameState gs; // Keeps track of the user's game state + + private static GameState gs; // Keeps track of the user's game state - private GameManager gameManager; // Game variables held here for multiplayer games + private static GameManager gameManager; // Game variables held here for multiplayer games - private JPanel cardLayoutPanels; // uses CardLayout to switch between menu and game - private CardLayout cl; + private static JPanel cardLayoutPanels; // uses CardLayout to switch between menu and game + private static CardLayout cl; // Panel Declarations - private JLayeredPane gameMasterLayer; // Master game panel, particularly for moving cards across entire screen - private SidePanel sidePanel; // Control panel on the side - private OperationPanel opPanel; // Panel that holds operations: + - / * - private CardPanel cardPanel; // Panel that holds cards at top - private WorkspacePanel workPanel; // Panel in the center of the screen where cards are morphed together - private HoldPanel holdPanel; // Panel that holds intermediate results - - /*TODO Values never used - Rectangle home1; - Rectangle home2; - Rectangle home3; - Rectangle home4; - Rectangle home5; - Rectangle home6; - */ - - Point[] placesHomes = new Point[12]; - - JLabel correct; - int answerA; - int answerS; - int answerM; - float answerD; - - int enterAction;// 0-3 - JButton random; - JButton clear; - - static boolean useDatabase = false; - private MySQLAccess sql; - private SwingWorker backgroundConnect; - private User thisUser; + private static JLayeredPane gameMasterLayer; // Master game panel, particularly for moving cards across entire screen + private static SidePanel sidePanel; // Control panel on the side + private static OperationPanel opPanel; // Panel that holds operations: + - / * + private static CardPanel cardPanel; // Panel that holds cards at top + private static WorkspacePanel workPanel; // Panel in the center of the screen where cards are morphed together + private static HoldPanel holdPanel; // Panel that holds intermediate results - JLabel correction; + public static boolean dbBackgroundConnectDone = false; + public static boolean dbConnected = false; - GridBagConstraints c; - - private JLabel[] cards = new JLabel[11]; // card1, card2..opA,S... - private Rectangle[] cardHomes = new Rectangle[11]; // home1, home2...opA,S... - private String[] cardVals = new String[11]; //TODO Use this variable or delete it + private static MySQLAccess sql; + private SwingWorker backgroundConnect; + private static User thisUser; + + /** + * cards[0] -> cards[5] are the number cards that the player uses (indexed from left to right when initialized) + *

+ * cards[6] is the answer card, which contains the result the player is trying to arrive at + *

+ * cards[7] -> cards[11] are the operation cards (addition, subtraction, multiplication, division, exponentiation) + */ + private static JLabel[] cards = new JLabel[12]; // card1, card2..opA,S... + + /** + * cards[0] -> cards[5] are the number cards that the player uses (indexed from left to right, when initialized) + *

+ * cards[6] is the answer card, which contains the result the player is trying to arrive at + *

+ * cards[7] -> cards[11] are the operation cards (addition, subtraction, multiplication, division, exponentiation) + */ + private static Rectangle[] cardHomes = new Rectangle[12]; // home1, home2...opA,S... - private TypeManager typeManager; + private static TypeManager typeManager; - private CompMover mover; + private static CompMover mover; - SoundManager sounds; + /** + * This function needs to be called after the database connection is established + * + */ + public static void backgroundInit(){ + if(!typeManager.isOffline()) + gameManager = new GameManager(); // Since this requires the connection to be established + + sidePanel = new SidePanel(); // Control bar + sidePanel.init(); + + multiMenu = new MultiMenu(); + multiMenu.init(); + multiMenu.setBounds(0, 0, size.width, size.height); + + hostMenu = new HostMenu(); + hostMenu.setBounds(0, 0, size.width, size.height); + + cardLayoutPanels.add(multiMenu, Menu.MULTIMENU.cardLayoutString); + cardLayoutPanels.add(hostMenu, Menu.HOSTMENU.cardLayoutString); + + gameMasterLayer.add(sidePanel, new Integer(0)); + } /** * Initializes the window & game @@ -140,14 +168,13 @@ public static enum GameState { public MathGame() { System.out.println("initing"); - thisUser = new User("blank", "pass"); - setPreferredSize(new Dimension(appWidth, appHeight)); - // setSize(appWidth, appHeight); + thisUser = new User("user", "pass"); + setPreferredSize(size); setLayout(null); - // ((JComponent) getContentPane()).setBorder(new - // LineBorder(Color.yellow)); - // setBorder(new LineBorder(Color.yellow)); sql = new MySQLAccess(this); + + typeManager = new TypeManager(); + backgroundConnect = new SwingWorker() { @Override @@ -155,11 +182,18 @@ protected Boolean doInBackground() throws Exception { try { if (!sql.connect()) { - throw new Exception("couldn't connect"); + if(!sql.displayUserConnectAgain()) + { + LoginMenu.connectAgain.setVisible(true); + return false; + } + else + return true; } System.out.println("Database connected"); return true; } catch (Exception e) { + typeManager.setOffline(true); System.out.println("Exception detected in doinBackground"); e.printStackTrace(); return false; @@ -186,9 +220,24 @@ protected void done() { } System.out.println("Done connected status " + connected); - if (connected) + if (connected) { for (int i = 0; i < 10; i++) System.out.println("CONNNNNNNNNECTEDDDDDD TO db"); + typeManager.setOffline(false);//one way to debug offline is to set this value true, but make sure to change it back! + dbConnected = true; + dbBackgroundConnectDone = true; + backgroundInit(); + } + else { + backgroundInit(); + GameDialogFactory.showGameMessageDialog( + MathGame.getCardPanel().getParent(), + "Offline", "Cannot connect to internet. Initiating offline mode", GameDialogFactory.OK); + typeManager.setOffline(true); + showMenu(Menu.MAINMENU); + dbConnected = false; + } + } }; @@ -196,162 +245,102 @@ protected void done() { // Initiation of panels cardLayoutPanels = new JPanel(new CardLayout()); - cardLayoutPanels.setBounds(0, 0, appWidth, appHeight); - + cardLayoutPanels.setBounds(0, 0, size.width, size.height); + + loginMenu = new LoginMenu(); + loginMenu.setBounds(0, 0, size.width, size.height); + + registerMenu = new RegisterMenu(); + registerMenu.setBounds(0, 0, size.width, size.height); + mainMenu = new MainMenu(); - mainMenu.init(this); - mainMenu.setBounds(0, 0, appWidth, appHeight); + mainMenu.init(); + mainMenu.setBounds(0, 0, size.width, size.height); gameMasterLayer = new JLayeredPane(); gameMasterLayer.setLayout(null); - gameMasterLayer.setBounds(5, 0, getSize().width, getSize().height); - - typeManager = new TypeManager(this); - gameManager = new GameManager(this); - - multiMenu = new MultiMenu(); - multiMenu.init(this, typeManager); - multiMenu.setBounds(0, 0, appWidth, appHeight); - - hostMenu = new HostMenu(this); - hostMenu.setBounds(0, 0, appWidth, appHeight); - - optionMenu = new OptionMenu(this); - optionMenu.setBounds(0, 0, appWidth, appHeight); + gameMasterLayer.setBounds(5, 0, size.width, size.height);//originally used getSize function - mover = new CompMover(this); - - sidePanel = new SidePanel(); // Control bar - // sidePanel.setBounds(750, 0, 900, 620);//x, y, width, height - sidePanel.init(this); + mover = new CompMover(); - cardPanel = new CardPanel(this); // Top card panel - // cardPanel.setBounds(0, 0, 750, 150); - cardPanel.init(gameMasterLayer); + cardPanel = new CardPanel(); // Top card panel + cardPanel.init(); opPanel = new OperationPanel(); // Operation panel opPanel.setBounds(0, 150, 750, 60); - opPanel.init(this, mover); + opPanel.init(); workPanel = new WorkspacePanel(); workPanel.setBounds(0, 210, 750, 260); - workPanel.init(this); + workPanel.init(); + holdPanel = new HoldPanel(); holdPanel.setBounds(0, 470, 750, 150); - holdPanel.init(this); - + holdPanel.init(); + // Adding panels to the game + cardLayoutPanels.add(loginMenu, Menu.LOGIN.cardLayoutString); + cardLayoutPanels.add(registerMenu, Menu.REGISTER.cardLayoutString); cardLayoutPanels.add(mainMenu, Menu.MAINMENU.cardLayoutString); cardLayoutPanels.add(gameMasterLayer, Menu.GAME.cardLayoutString); - cardLayoutPanels.add(multiMenu, Menu.MULTIMENU.cardLayoutString); - cardLayoutPanels.add(optionMenu, Menu.OPTIONMENU.cardLayoutString); - cardLayoutPanels.add(hostMenu, Menu.HOSTMENU.cardLayoutString); cl = (CardLayout) cardLayoutPanels.getLayout(); // cl.show(cardLayoutPanels, MENU); add(cardLayoutPanels); - showMenu(Menu.MAINMENU); + showMenu(Menu.LOGIN); // add(layer); // layer.add(menu, new Integer(2)); - gameMasterLayer.add(sidePanel, new Integer(0)); gameMasterLayer.add(opPanel, new Integer(0)); gameMasterLayer.add(cardPanel, new Integer(0)); gameMasterLayer.add(workPanel, new Integer(0)); gameMasterLayer.add(holdPanel, new Integer(0)); - /* - home1 = new Rectangle(cardPanel.card1.getBounds()); - home2 = new Rectangle(cardPanel.card2.getBounds()); - home3 = new Rectangle(cardPanel.card3.getBounds()); - home4 = new Rectangle(cardPanel.card4.getBounds()); - home5 = new Rectangle(cardPanel.card5.getBounds()); - home6 = new Rectangle(cardPanel.card6.getBounds()); - */ - - cardHomes[0] = cardPanel.card1.getBounds(); - cardHomes[1] = cardPanel.card2.getBounds(); - cardHomes[2] = cardPanel.card3.getBounds(); - cardHomes[3] = cardPanel.card4.getBounds(); - cardHomes[4] = cardPanel.card5.getBounds(); - cardHomes[5] = cardPanel.card6.getBounds(); - cardHomes[6] = cardPanel.ans.getBounds(); + DropTarget dt = new DropTarget(); + dt.setActive(false); + + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cardHomes[i] = cardPanel.getCards()[i].getBounds(); + cards[i] = cardPanel.getCards()[i]; + cardPanel.getCards()[i].setTransferHandler(new TransferHandler("text")); + cardPanel.getCards()[i].setDropTarget(dt); + cardPanel.getCards()[i].addMouseListener(mover); + cardPanel.getCards()[i].addMouseMotionListener(mover); + gameMasterLayer.add(cardPanel.getCards()[i], new Integer(1)); // Adding new integer ensures card is on top + } + cardHomes[6] = cardPanel.getAns().getBounds(); cardHomes[7] = opPanel.add.getBounds(); cardHomes[8] = opPanel.subtract.getBounds(); cardHomes[9] = opPanel.multiply.getBounds(); cardHomes[10] = opPanel.divide.getBounds(); + cardHomes[11] = opPanel.exponent.getBounds(); - cards[0] = cardPanel.card1; - cards[1] = cardPanel.card2; - cards[2] = cardPanel.card3; - cards[3] = cardPanel.card4; - cards[4] = cardPanel.card5; - cards[5] = cardPanel.card6; - cards[6] = cardPanel.ans; + cards[6] = cardPanel.getAns(); cards[7] = opPanel.add; cards[8] = opPanel.subtract; cards[9] = opPanel.multiply; cards[10] = opPanel.divide; - - cardPanel.card1.setTransferHandler(new TransferHandler("text")); - cardPanel.card2.setTransferHandler(new TransferHandler("text")); - cardPanel.card3.setTransferHandler(new TransferHandler("text")); - cardPanel.card4.setTransferHandler(new TransferHandler("text")); - cardPanel.card5.setTransferHandler(new TransferHandler("text")); - cardPanel.card6.setTransferHandler(new TransferHandler("text")); - // cardPanel.ans.setTransferHandler(new TransferHandler("text")); - - DropTarget dt = new DropTarget(); - dt.setActive(false); - cardPanel.card1.setDropTarget(dt); - cardPanel.card2.setDropTarget(dt); - cardPanel.card3.setDropTarget(dt); - cardPanel.card4.setDropTarget(dt); - cardPanel.card5.setDropTarget(dt); - cardPanel.card6.setDropTarget(dt); - // cardPanel.ans.setDropTarget(dt); - - //ACTION LISTENERS - - // Handles 6 cards - cardPanel.card1.addMouseListener(mover); - cardPanel.card2.addMouseListener(mover); - cardPanel.card3.addMouseListener(mover); - cardPanel.card4.addMouseListener(mover); - cardPanel.card5.addMouseListener(mover); - cardPanel.card6.addMouseListener(mover); - // cardPanel.ans.addMouseListener(mover); - - cardPanel.card1.addMouseMotionListener(mover); - cardPanel.card2.addMouseMotionListener(mover); - cardPanel.card3.addMouseMotionListener(mover); - cardPanel.card4.addMouseMotionListener(mover); - cardPanel.card5.addMouseMotionListener(mover); - cardPanel.card6.addMouseMotionListener(mover); - // cardPanel.ans.addMouseMotionListener(mover); + cards[11] = opPanel.exponent; // Handles 4 operations opPanel.add.addMouseListener(mover); opPanel.subtract.addMouseListener(mover); opPanel.multiply.addMouseListener(mover); opPanel.divide.addMouseListener(mover); + opPanel.exponent.addMouseListener(mover); opPanel.add.addMouseMotionListener(mover); opPanel.subtract.addMouseMotionListener(mover); opPanel.multiply.addMouseMotionListener(mover); opPanel.divide.addMouseMotionListener(mover); + opPanel.exponent.addMouseMotionListener(mover); + // Adds to layered pane to facilitate movement across ALL panels - gameMasterLayer.add(cardPanel.card1, new Integer(1)); // Adding new integer ensures card is on top - gameMasterLayer.add(cardPanel.card2, new Integer(1)); - gameMasterLayer.add(cardPanel.card3, new Integer(1)); - gameMasterLayer.add(cardPanel.card4, new Integer(1)); - gameMasterLayer.add(cardPanel.card5, new Integer(1)); - gameMasterLayer.add(cardPanel.card6, new Integer(1)); - - gameMasterLayer.add(cardPanel.ans, new Integer(1)); // Holds the answer + gameMasterLayer.add(cardPanel.getAns(), new Integer(1)); // Holds the answer gameMasterLayer.add(opPanel.add, new Integer(1)); gameMasterLayer.add(opPanel.subtract, new Integer(1)); gameMasterLayer.add(opPanel.multiply, new Integer(1)); gameMasterLayer.add(opPanel.divide, new Integer(1)); + gameMasterLayer.add(opPanel.exponent, new Integer(1)); /* * //Code for a different Cursor Toolkit toolkit = getToolkit(); Image @@ -363,21 +352,14 @@ protected void done() { * setCursor(lightPenCursor); layer.setCursor(imageCursor); */ - sounds = new SoundManager(this); - System.out.println("init done"); } - - @Override - public void actionPerformed(ActionEvent evt) { - - } /** * Displays the desired menu/window * @param menu - The Menu to show */ - public void showMenu(Menu menu) { + public static void showMenu(Menu menu) { cl.show(cardLayoutPanels, menu.cardLayoutString); } @@ -385,14 +367,16 @@ public void showMenu(Menu menu) { * @param menu - The Menu to get * @return The corresponding menu (as a JPanel) */ - public JPanel getMenu(Menu menu) { + public static JPanel getMenu(Menu menu) { switch (menu) { + case LOGIN: + return loginMenu; + case REGISTER: + return registerMenu; case MAINMENU: return mainMenu; case MULTIMENU: return multiMenu; - case OPTIONMENU: - return optionMenu; case HOSTMENU: return hostMenu; default: @@ -403,112 +387,133 @@ public JPanel getMenu(Menu menu) { /** * @return The game state of the MathGame object */ - public GameState getGameState() { + public static GameState getGameState() { return gs; } /** * @param gs - The game state to set */ - public void setGameState(GameState gs) { - this.gs = gs; + public static void setGameState(GameState gs) { + MathGame.gs = gs; } /** * @return The TypeManager of the MathGame object */ - public TypeManager getTypeManager() { + public static TypeManager getTypeManager() { return typeManager; } /** * @return The GameManager of the MathGame object */ - public GameManager getGameManager() { + public static GameManager getGameManager() { return gameManager; } /** * @return The master panel (layer) of the MathGame object */ - public JLayeredPane getMasterPane() { + public static JLayeredPane getMasterPane() { return gameMasterLayer; } /** * @return The SidePanel of the MathGame object */ - public SidePanel getSidePanel() { + public static SidePanel getSidePanel() { return sidePanel; } /** * @return The OperationPanel of the MathGame object */ - public OperationPanel getOperationPanel() { + public static OperationPanel getOperationPanel() { return opPanel; } /** * @return The CardPanel of the MathGame object */ - public CardPanel getCardPanel() { + public static CardPanel getCardPanel() { return cardPanel; } /** * @return The WorkspacePanel of the MathGame object */ - public WorkspacePanel getWorkspacePanel() { + public static WorkspacePanel getWorkspacePanel() { return workPanel; } /** * @return The HoldPanel of the MathGame object */ - public HoldPanel getHoldPanel() { + public static HoldPanel getHoldPanel() { return holdPanel; } /** - * @return A JLabel array of all Cards (NumberCards and OperationCards) + * @return The JLabel array of all Cards (NumberCards and OperationCards) */ - public JLabel[] getCards() { + public static JLabel[] getCards() { return cards; } /** - * @return A Rectangle array of all Card bounds + * @return The Rectangle array of all Card bounds */ - public Rectangle[] getCardHomes() { + public static Rectangle[] getCardHomes() { return cardHomes; } - - /** - * @return A String array of all NumberCard values - */ - public String[] getCardVals() { - return cardVals; - } /** * @return The MySQLAccess object of the MathGame object */ - public MySQLAccess getMySQLAccess() { + public static MySQLAccess getMySQLAccess() { return sql; } /** - * @return The current user (associated with the MathGame object) + * @return The current user (that is associated with the MathGame object) */ - public User getUser() { + public static User getUser() { return thisUser; } /** * @return The CompMover object of the MathGame object */ - public CompMover getCompMover() { + public static CompMover getCompMover() { return mover; } + + /** + * @return True if connected to the database + */ + public static boolean isDbConnected() { + return dbConnected; + } + + /** + * @return The width of the MathGame application + */ + public static int getAppWidth() { + return MathGame.size.width; + } + + /** + * @return The height of the MathGame application + */ + public static int getAppHeight() { + return MathGame.size.height; + } + + /** + * @return The Dimension of the MathGame application + */ + public static Dimension getAppSize() { + return MathGame.size; + } } \ No newline at end of file diff --git a/src/com/mathgame/math/SoundManager.java b/src/com/mathgame/math/SoundManager.java index 6f44f4e..3327574 100644 --- a/src/com/mathgame/math/SoundManager.java +++ b/src/com/mathgame/math/SoundManager.java @@ -2,20 +2,14 @@ import java.applet.Applet; import java.applet.AudioClip; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.WindowConstants; /** * The SoundManager class is responsible for the sound effects and volume control of the Math Game + * @author Raziq, David K. */ -public class SoundManager implements ActionListener { +public class SoundManager { private static Boolean musicPlay = true; @@ -54,7 +48,13 @@ public static enum SoundType { *

* Source: https://www.freesound.org/people/timgormly/sounds/181857/ */ - INCORRECT (Applet.newAudioClip(SoundManager.class.getResource("/audio/incorrect.wav"))); + INCORRECT (Applet.newAudioClip(SoundManager.class.getResource("/audio/incorrect.wav"))), + + WAIT (Applet.newAudioClip(SoundManager.class.getResource("/audio/wait.wav"))), + + WIN (Applet.newAudioClip(SoundManager.class.getResource("/audio/win.wav"))), + + LOSE (Applet.newAudioClip(SoundManager.class.getResource("/audio/lose.wav"))); private final AudioClip sfx; SoundType(AudioClip sfx) { @@ -62,29 +62,10 @@ public static enum SoundType { } }; - JButton mButton; - - public SoundManager(MathGame mathgame) { - JFrame mButtonFrame = new JFrame("Audio"); - mButtonFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - - JPanel mButtonPanel = new JPanel(); - - mButton = new JButton(soundIcon); - mButton.addActionListener(this); - - mButtonPanel.add(mButton); - - mButtonFrame.getContentPane().add(mButtonPanel); - mButtonFrame.pack(); - mButtonFrame.setLocation(new Point(mathgame.getX()+mathgame.appWidth, mathgame.getY()+mathgame.appHeight)); - mButtonFrame.setVisible(true); - } - /** * Toggles the music, turning it on or off */ - public static void toggleMusic() { + private static void toggleMusic() { musicPlay = !musicPlay; } @@ -97,13 +78,26 @@ public static void playSound(SoundType type) { type.sfx.play(); } } + + public static void loopSound(SoundType type) { + if (musicPlay) { + type.sfx.loop(); + } + } /** * When the volume button is pressed, it is toggled, also changing the icon image + * @return The image icon that the button should be set to */ - @Override - public void actionPerformed(ActionEvent e) { + public static ImageIcon volumeButtonPressed() { toggleMusic(); - mButton.setIcon(musicPlay? soundIcon : muteIcon); + return currentVolumeButtonImage(); + } + + /** + * @return The image icon that the button should be set to + */ + public static ImageIcon currentVolumeButtonImage() { + return (musicPlay? soundIcon : muteIcon); } } diff --git a/src/com/mathgame/math/TypeManager.java b/src/com/mathgame/math/TypeManager.java index 8102988..886a057 100644 --- a/src/com/mathgame/math/TypeManager.java +++ b/src/com/mathgame/math/TypeManager.java @@ -1,104 +1,142 @@ package com.mathgame.math; import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Iterator; import java.util.Random; import com.mathgame.cards.NumberCard; import com.mathgame.database.MySQLAccess; +import com.mathgame.network.GameManager; import com.mathgame.panels.CardPanel; +import com.mysql.jdbc.*; +import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * The TypeManager handles the different types of games and converts between values of different types */ public class TypeManager { - static MathGame mathGame; - MySQLAccess sql; - - NumberCard card1; - NumberCard card2; - NumberCard card3; - NumberCard card4; - NumberCard card5; - NumberCard card6; - NumberCard ans; - - CardPanel cP; + private MySQLAccess sql; - ArrayList values; - ArrayList cardExists; + private CardPanel cP; + static int index = 0; + private ArrayList values; /** * The GameType enumeration is used to distinguish between game types */ public static enum GameType { - INTEGERS, - DECIMALS, - FRACTIONS, - MIXED + INTEGERS ("Integers"), + DECIMALS ("Decimals"), + FRACTIONS ("Fractions"), + EXPONENTS ("Exponents"), + LOGARITHMS ("Logarithms"); + + public final String gameTypeString; + GameType(String gameTypeString) { + this.gameTypeString = gameTypeString; + } }; /** * The Difficulty enumeration is used to distinguish between levels of difficulty */ public static enum Difficulty { - EASY, - MEDIUM, - HARD + EASY ("Easy"), + MEDIUM ("Medium"), + HARD ("Hard"); + + public final String difficultyString; + Difficulty(String difficultyString) { + this.difficultyString = difficultyString; + } }; - GameType gameType; - Difficulty gameDiff; + private boolean offline; + private EnumSet gameType; + private Difficulty gameDiff; + + //for offline play: + InputStream cardValueInput; + XSSFWorkbook cardValueWorkbook; + static final String INTEGERS_FILE = "spreadsheets/Integers.xlsx"; + static final String FRACTIONS_FILE = "spreadsheets/Fractions.xlsx"; + static final String DECIMALS_FILE = "spreadsheets/Decimals.xlsx"; + static final String EXPONENTS_FILE = "spreadsheets/Exponents.xlsx"; + static final String LOGARITHMS_FILE = "spreadsheets/Logarithms.xlsx"; + private XSSFSheet currentSheet; + private int rowCount; + private int currentRowNumber; + private XSSFRow currentRow; - public TypeManager(MathGame mathGame) { - TypeManager.mathGame = mathGame; - sql = mathGame.getMySQLAccess(); - gameType = GameType.INTEGERS; + public TypeManager() { + sql = MathGame.getMySQLAccess(); + gameType = EnumSet.of(GameType.INTEGERS);//default is integers } /** * Set the type of numbers being worked with. - * Use the following keywords: fraction; decimal; integer * - * Default number type is integer * @param type - The GameType of the game to set */ - public void setType(GameType type) { + public void setType(EnumSet type) { gameType = type; - System.out.println("GameType " + gameType); + System.out.println("GameType " + gameType.toString()); } /** * Set the type of numbers being worked with. - * Use the following keywords: fraction; decimal; integer * - * Default number type is integer * @param type - The type of game to set (as a string) */ public void setType(String type) { - if (type.equals("Integer")) { - gameType = GameType.INTEGERS; - } else if (type.equals("Fraction")) { - gameType = GameType.FRACTIONS; - } else if (type.equals("Decimal")) { - gameType = GameType.DECIMALS; - } else if (type.equals("Mixed")) { - gameType = GameType.MIXED; - } else { - System.err.println("GAME TYPE NOT FOUND ABORT"); + for(GameType g : GameType.values()){ + if(type.equals(g.gameTypeString)) { + gameType.add(g); + System.out.println("Added GameType " + gameType); + return; + } } - - System.out.println("GameType " + gameType); + System.err.println("GAME TYPE NOT FOUND ABORT"); } + /** + * Adds game type to enumset gametype + * @param g + */ + public void addType(GameType g) { + gameType.add(g); + } + + /** + * Clears the type + */ + public void clearType() { + gameType.clear(); + } + /** * @return The GameType of the game */ - public GameType getType() { + public EnumSet getType() { return gameType; } @@ -109,48 +147,47 @@ public void setDiff(Difficulty d) { gameDiff = d; } + /** + * @param diff - The Difficulty of game to set as string + */ + public void setDiff(String diff) { + for(Difficulty d : Difficulty.values()){ + if(diff.equals(d.difficultyString)) { + gameDiff = d; + System.out.println("Difficulty " + gameDiff); + return; + } + } + System.err.println("DIFF TYPE NOT FOUND ABORT"); + } + /** * @return The Difficulty of the game */ public Difficulty getDiff() { return gameDiff; } - - public void init(CardPanel cP) { - this.cP = cP; - this.card1 = cP.card1; - this.card2 = cP.card2; - this.card3 = cP.card3; - this.card4 = cP.card4; - this.card5 = cP.card5; - this.card6 = cP.card6; - this.ans = cP.ans; - this.values = cP.values; + /** + * @return the offline + */ + public boolean isOffline() { + return offline; } /** - * @return A randomly generated ArrayList of fractions (stored as doubles) + * @param offline the offline to set */ - public ArrayList randomFractionValues() { - Random generator = new Random(); - Random fractionRand = new Random(); - - ArrayList cardValues = new ArrayList(); - - for (int x = 0; x < 6; x++) { - cardValues.add(((int)(fractionRand.nextDouble() * 10)) / 10.0); - } - int RandomInsert1 = (int)(generator.nextFloat() * 6); - int RandomInsert2; - do { - RandomInsert2 = (int)(generator.nextFloat() * 6); - } while (RandomInsert2 == RandomInsert1 ); // The two values must be in distinct NumberCards (i.e. not the same card!) - - cardValues.set(RandomInsert1, convertFractiontoDecimal(sql.getNum1())); - cardValues.set(RandomInsert2, convertFractiontoDecimal(sql.getNum2())); - - return cardValues; + public void setOffline(boolean offline) { + this.offline = offline; + } + + /** + * @param cP - The CardPanel which the game cards are from + */ + public void init(CardPanel cP) { + this.cP = cP; + this.values = cP.values; } /** @@ -232,7 +269,7 @@ public static String convertDecimaltoFraction(double input) { x = x.abs(); } - BigDecimal error = new BigDecimal("0.000001"); //TODO Should this be changed to MathGame.epsilon? + BigDecimal error = new BigDecimal(MathGame.epsilon); x = x.setScale(error.scale(), RoundingMode.HALF_UP); BigDecimal n = (new BigDecimal(x.toBigInteger())).setScale(error.scale()); @@ -279,166 +316,291 @@ public static String convertDecimaltoFraction(double input) { } } - /** - * @return A randomly generated ArrayList of decimals - */ - public ArrayList randomDecimalValues() { - Random generator = new Random(); - - ArrayList cardValues = new ArrayList(); - - for (int x = 0; x < 6; x++) { - int temp = (int)(generator.nextDouble()*100); - cardValues.add( temp/100.0 ); //TODO Fix random decimal generation - } + private int getSeed() throws SQLException{ + if(!MathGame.getTypeManager().isOffline()){ + MysqlDataSource ds = new MysqlDataSource(); + ds.setUser("sofiav_user"); + ds.setPassword("Mathgames1"); + ds.setServerName("mcalearning.com"); + //ds.setDatabaseName("sofiav_mathgame"); - int RandomInsert1 = (int)(generator.nextFloat() * 6); - int RandomInsert2 = (int)(generator.nextFloat() * 6); - while (RandomInsert2 == RandomInsert1) { - RandomInsert2 = (int)(generator.nextFloat() * 6); + // For testing, it should be mcalearning + String host = "mcalearning.com"; // "192.185.4.77"; + String db = "sofiav_mathgame"; + final String user = "sofiav_user"; // "egarciao@localhost"; + final String pass = "Mathgames1"; //"oL20wC06xd"; + + + Connection conn; + conn = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + "/" + db, user, pass); + + Statement stmt = (Statement) conn.createStatement(); + + //55 = lobby number + index = index % 6; + Random gen = new Random(); + // System.out.println(GameManager.getMatchesAccess().getMatchNum() * GameManager.getMatchesAccess().getCurrentRound() % 34000 + " hello"); + ResultSet rs = null; + System.out.println(gen.nextInt() % 34000+" hjkjhj"); + if(MathGame.getGameState().equals(MathGame.GameState.PRACTICE)){ + + rs = stmt.executeQuery("select seed from sofiav_mathgame.seed where seed_id = " + Math.abs(( gen.nextInt() % 34000))); + } + else{ + rs = stmt.executeQuery("select seed from sofiav_mathgame.seed where seed_id = " + ( GameManager.getMatchesAccess().getMatchNum() * GameManager.getMatchesAccess().getCurrentRound() % 34000)); + } + + index++; + rs.next(); + System.out.println(rs.getInt(1)); + int thingie = rs.getInt(1); + conn.close(); + return thingie;} + else{ + Random ran = new Random(); + return ran.nextInt(); } - - cardValues.set(RandomInsert1, Double.valueOf(sql.getNum1())); - cardValues.set(RandomInsert2, Double.valueOf(sql.getNum2())); - - return cardValues; } /** - * @return A randomly generated ArrayList of integers + * Generates a list of random values for use by randomize function + * @param types + * @return + * @throws SQLException */ - public ArrayList randomIntegerValues() { - Random generator = new Random(); - - ArrayList cardValues = new ArrayList(); - - for (int x = 0; x < 6; x++) { - cardValues.add(generator.nextInt(21)); + private ArrayList randomValues(EnumSet types) throws SQLException { + ArrayList cardVals = new ArrayList(); + Random gen = new Random(); + int seed = getSeed(); + gen.setSeed(seed); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + //select the type that will be the next card (that is a member of the types selected by user) + int rand = gen.nextInt(5); + while(!types.contains(GameType.values()[rand])){ + + rand = gen.nextInt(5); + System.out.println("rand is equal to " + rand); + } + System.out.println("rand is " + rand); + switch(rand) { + case 0://integers + cardVals.add(String.valueOf(gen.nextInt(21)));//add a value between 0 and 20 + break; + case 1://decimals + cardVals.add(String.valueOf(((int)(gen.nextDouble() * 100))/10.0));//generates decimal to tenth place + break; + case 2://fractions + int num = gen.nextInt(11) + 1; + int den = gen.nextInt(11) + 1; + while(num % den == 0) + den = gen.nextInt(11) + 1; + cardVals.add(String.valueOf(num) + "/" + String.valueOf(den)); + break; + case 3://exponents + int base = gen.nextInt(10) + 1;//from 1 to 6 + if(base < 6) + cardVals.add(String.valueOf(base) + "^" + String.valueOf(gen.nextInt(7 - base))); + else + cardVals.add(String.valueOf(base) + "^" + String.valueOf(gen.nextInt(3))); + //bases 6+ are limited to powers of 0, 1 or 2 + break; + case 4://logs + int base2 = gen.nextInt(9) + 2; + if(base2 < 6)//if the base is less than 6, the power, i.e. answer, is between 0 and 7 - base + cardVals.add("log_"+String.valueOf(base2) + "(" + String.valueOf((int)Math.pow(base2, gen.nextInt(7 - base2))) + ")"); + else//otherwise answer can only be 0, 1, or 2 (it'll be too high otherwise) + cardVals.add("log_"+String.valueOf(base2) + "(" + String.valueOf((int)Math.pow(base2, gen.nextInt(3))) + ")"); + break; + } } + /* + switch(types) { + case INTEGERS: + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) + cardVals.add(String.valueOf(gen.nextInt(21)));//add a value between 0 and 20 + break; + case DECIMALS: + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) + cardVals.add(String.valueOf(((int)(gen.nextDouble() * 100))/10.0));//generates decimal to tenth place + break; + case FRACTIONS: + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + int num = gen.nextInt(11); + int den = gen.nextInt(11) + 1; + while(num % den == 0) { + den = gen.nextInt(11) + 1; + } + cardVals.add(String.valueOf(num) + "/" + String.valueOf(den)); + } + break; + case EXPONENTS: + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + int base = gen.nextInt(10) + 1;//from 1 to 6 + if(base < 6) + cardVals.add(String.valueOf(base) + "^" + String.valueOf(gen.nextInt(7 - base))); + else + cardVals.add(String.valueOf(base) + "^" + String.valueOf(gen.nextInt(3))); + //bases 6+ are limited to powers of 0, 1 or 2 + } + break; + case LOGARITHMS: + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + int base = gen.nextInt(9) + 2; + if(base < 6)//if the base is less than 6, the power, i.e. answer, is between 0 and 7 - base + cardVals.add("log_"+String.valueOf(base) + "(" + String.valueOf((int)Math.pow(base, gen.nextInt(7 - base))) + ")"); + else//otherwise answer can only be 0, 1, or 2 (it'll be too high otherwise) + cardVals.add("log_"+String.valueOf(base) + "(" + String.valueOf((int)Math.pow(base, gen.nextInt(3))) + ")"); + } + break; + case MIXED: + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + switch(gen.nextInt(5)) { + case 0://integers + cardVals.add(String.valueOf(gen.nextInt(21)));//add a value between 0 and 20 + break; + case 1://decimals + cardVals.add(String.valueOf(((int)(gen.nextDouble() * 100))/10.0));//generates decimal to tenth place + break; + case 2://fractions + int num = gen.nextInt(11); + int den = gen.nextInt(11) + 1; + while(num % den == 0) { + den = gen.nextInt(11) + 1; + } + cardVals.add(String.valueOf(num) + "/" + String.valueOf(den)); + break; + case 3://exponents + int base = gen.nextInt(10) + 1;//from 1 to 6 + if(base < 6) + cardVals.add(String.valueOf(base) + "^" + String.valueOf(gen.nextInt(7 - base))); + else + cardVals.add(String.valueOf(base) + "^" + String.valueOf(gen.nextInt(3))); + //bases 6+ are limited to powers of 0, 1 or 2 + break; + case 4://logs + int base2 = gen.nextInt(9) + 2; + if(base2 < 6)//if the base is less than 6, the power, i.e. answer, is between 0 and 7 - base + cardVals.add("log_"+String.valueOf(base2) + "(" + String.valueOf((int)Math.pow(base2, gen.nextInt(7 - base2))) + ")"); + else//otherwise answer can only be 0, 1, or 2 (it'll be too high otherwise) + cardVals.add("log_"+String.valueOf(base2) + "(" + String.valueOf((int)Math.pow(base2, gen.nextInt(3))) + ")"); + break; + } + } + break; + }*/ + System.out.println("about to make randominserts"); - int RandomInsert1 = (int)(generator.nextFloat() * 6); - int RandomInsert2 = (int)(generator.nextFloat() * 6); - while (RandomInsert2 == RandomInsert1) { - RandomInsert2 = (int)(generator.nextFloat() * 6); - } + int RandomInsert1 = (int)(gen.nextFloat() * CardPanel.NUM_OF_CARDS); + int RandomInsert2 = (int)(gen.nextFloat() * CardPanel.NUM_OF_CARDS); + while (RandomInsert2 == RandomInsert1) + RandomInsert2 = (int)(gen.nextFloat() * CardPanel.NUM_OF_CARDS); + + if(!offline) {//use database + cardVals.set(RandomInsert1, sql.getNum1()); + cardVals.set(RandomInsert2, sql.getNum2()); + } else { + //select the type table (that is a member of the types selected by user) + int rand = gen.nextInt(5); + while(!types.contains(GameType.values()[rand])) + rand = gen.nextInt(5); + GameType tableGameType = GameType.values()[rand]; + try { + //ideally we'd use enums for these file names or something... yuck yuck yuck + if(tableGameType == GameType.INTEGERS) + cardValueInput = getClass().getClassLoader().getResourceAsStream(INTEGERS_FILE); + else if(tableGameType == GameType.FRACTIONS) + cardValueInput = getClass().getClassLoader().getResourceAsStream(FRACTIONS_FILE); + else if(tableGameType == GameType.DECIMALS) + cardValueInput = getClass().getClassLoader().getResourceAsStream(DECIMALS_FILE); + else if(tableGameType == GameType.EXPONENTS) + cardValueInput = getClass().getClassLoader().getResourceAsStream(EXPONENTS_FILE); + else if(tableGameType == GameType.LOGARITHMS) + cardValueInput = getClass().getClassLoader().getResourceAsStream(LOGARITHMS_FILE); - cardValues.set(RandomInsert1, Integer.valueOf(sql.getNum1())); - cardValues.set(RandomInsert2, Integer.valueOf(sql.getNum2())); // (int)(currentRow.getCell(3).getNumericCellValue())); + System.out.println("file size: " + cardValueInput.available()); + cardValueWorkbook = new XSSFWorkbook(cardValueInput); - return cardValues; + currentSheet = cardValueWorkbook.getSheetAt(0); + Iterator rowIter = currentSheet.rowIterator(); + rowCount = 0; + while(rowIter.hasNext()) { + rowCount++; + rowIter.next(); + } + } catch (FileNotFoundException e) { + System.out.println("excel file not found"); + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + currentRowNumber = (int)(gen.nextFloat() * rowCount); + System.out.println("Current row: " + (currentRowNumber + 1)); + currentRow = currentSheet.getRow(currentRowNumber); + + if(currentRow.getCell(1).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) + { + cardVals.set(RandomInsert1, String.valueOf(currentRow.getCell(1).getNumericCellValue())); + cardVals.set(RandomInsert2, String.valueOf(currentRow.getCell(3).getNumericCellValue())); + } else { + cardVals.set(RandomInsert1, currentRow.getCell(1).getStringCellValue()); + cardVals.set(RandomInsert2, currentRow.getCell(3).getStringCellValue()); + } + + try { + cardValueInput.close(); + } catch (IOException e) { + System.out.println("Could not close input stream"); + e.printStackTrace(); + } + } + return cardVals; } - + /** * Assigns random values to the number cards + * @throws Exception */ - public void randomize() { - try { - if (sql.getConnection() == null) { - sql.connect(); + public void randomize() throws Exception { + if(!MathGame.getTypeManager().isOffline()) { + try { + if (sql.getConnection() == null) { + sql.connect(); + } + sql.getVals(); + // mathGame.sql.close(); + } catch (Exception e) { + System.out.println("Get vals from DB failed"); + e.printStackTrace(); } - sql.getVals(); - // mathGame.sql.close(); - } catch (Exception e) { - System.out.println("Get vals from DB failed"); - e.printStackTrace(); } - System.out.println("\n\n\n\n*******GAMETYPE=="+gameType+"**********\n\n\n"); + System.out.println("\n*******GAMETYPE=="+gameType+"**********\n"); - if (gameType == GameType.FRACTIONS) { - ArrayList newValues = randomFractionValues(); - - card1.setStrValue(convertDecimaltoFraction(newValues.get(0))); - card2.setStrValue(convertDecimaltoFraction(newValues.get(1))); - card3.setStrValue(convertDecimaltoFraction(newValues.get(2))); - card4.setStrValue(convertDecimaltoFraction(newValues.get(3))); - card5.setStrValue(convertDecimaltoFraction(newValues.get(4))); - card6.setStrValue(convertDecimaltoFraction(newValues.get(5))); - - values.set(0, card1.getStrValue()); - values.set(1, card2.getStrValue()); - values.set(2, card3.getStrValue()); - values.set(3, card4.getStrValue()); - values.set(4, card5.getStrValue()); - values.set(5, card6.getStrValue()); - ans.setStrValue(sql.getAnswer()); - System.out.println(newValues.get(0)); - - card1.setValue(String.valueOf(newValues.get(0))); - card2.setValue(String.valueOf(newValues.get(1))); - card3.setValue(String.valueOf(newValues.get(2))); - card4.setValue(String.valueOf(newValues.get(3))); - card5.setValue(String.valueOf(newValues.get(4))); - card6.setValue(String.valueOf(newValues.get(5))); - ans.setValue(String.valueOf(NumberCard.parseNumFromText(ans.getStrValue()))); - // card1.parseNumFromText(newValues.get(3)) + ArrayList newVals = randomValues(gameType); + System.out.println("did randomValues"); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cP.getCards()[i].setStrValue(newVals.get(i)); + values.set(i, newVals.get(i)); + cP.getCards()[i].setValue(NumberCard.parseNumFromText((newVals.get(i)))); + System.out.println("hell"); } - - else if(gameType == GameType.DECIMALS) { - ArrayList newValues = randomDecimalValues(); - - card1.setStrValue(String.valueOf(newValues.get(0))); - card2.setStrValue(String.valueOf(newValues.get(1))); - card3.setStrValue(String.valueOf(newValues.get(2))); - card4.setStrValue(String.valueOf(newValues.get(3))); - card5.setStrValue(String.valueOf(newValues.get(4))); - card6.setStrValue(String.valueOf(newValues.get(5))); - - values.set(0, card1.getStrValue()); - values.set(1, card2.getStrValue()); - values.set(2, card3.getStrValue()); - values.set(3, card4.getStrValue()); - values.set(4, card5.getStrValue()); - values.set(5, card6.getStrValue()); - ans.setStrValue(sql.getAnswer()); - System.out.println(newValues.get(0)); - - - card1.setValue(String.valueOf(newValues.get(0))); - card2.setValue(String.valueOf(newValues.get(1))); - card3.setValue(String.valueOf(newValues.get(2))); - card4.setValue(String.valueOf(newValues.get(3))); - card5.setValue(String.valueOf(newValues.get(4))); - card6.setValue(String.valueOf(newValues.get(5))); - ans.setValue(String.valueOf(NumberCard.parseNumFromText(ans.getStrValue()))); + //obtain answer value from database/excel + if(offline) { + if(currentRow.getCell(4).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) + cP.getAns().setStrValue(String.valueOf(currentRow.getCell(4).getNumericCellValue())); + else + cP.getAns().setStrValue(currentRow.getCell(4).getStringCellValue()); } + else + cP.getAns().setStrValue(sql.getAnswer()); - else{ - ArrayList newValues = randomIntegerValues(); - - card1.setStrValue(String.valueOf(newValues.get(0))); - card2.setStrValue(String.valueOf(newValues.get(1))); - card3.setStrValue(String.valueOf(newValues.get(2))); - card4.setStrValue(String.valueOf(newValues.get(3))); - card5.setStrValue(String.valueOf(newValues.get(4))); - card6.setStrValue(String.valueOf(newValues.get(5))); - - values.set(0, card1.getStrValue()); - values.set(1, card2.getStrValue()); - values.set(2, card3.getStrValue()); - values.set(3, card4.getStrValue()); - values.set(4, card5.getStrValue()); - values.set(5, card6.getStrValue()); - ans.setStrValue(sql.getAnswer()); - System.out.println(newValues.get(0)); - - - card1.setValue(String.valueOf(newValues.get(0))); - card2.setValue(String.valueOf(newValues.get(1))); - card3.setValue(String.valueOf(newValues.get(2))); - card4.setValue(String.valueOf(newValues.get(3))); - card5.setValue(String.valueOf(newValues.get(4))); - card6.setValue(String.valueOf(newValues.get(5))); - ans.setValue(String.valueOf(NumberCard.parseNumFromText(ans.getStrValue()))); - } + cP.getAns().setValue(NumberCard.parseNumFromText(cP.getAns().getStrValue())); // Tag each card with "home" (cardPanel) being original location - card1.setHome("home"); - card2.setHome("home"); - card3.setHome("home"); - card4.setHome("home"); - card5.setHome("home"); - card6.setHome("home"); - ans.setHome("home"); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cP.getCards()[i].setHome("home"); + } + cP.getAns().setHome("home"); } } diff --git a/src/com/mathgame/math/Window.java b/src/com/mathgame/math/Window.java index eed328f..20c038f 100644 --- a/src/com/mathgame/math/Window.java +++ b/src/com/mathgame/math/Window.java @@ -8,29 +8,24 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; - import javax.swing.JFrame; - import com.mathgame.network.GameManager; /** * The Window class is where execution of Epsilon (the Math Game) begins */ public class Window { - - static MathGame mg; private static void createAndShowGUI() { JFrame frame = new JFrame("Epsilon"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - mg = new MathGame(); - frame.getContentPane().add(mg); + frame.getContentPane().add(new MathGame()); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new MathWindowListener()); - + frame.setLocationRelativeTo(null);//center the game on screen frame.setVisible(true); } @@ -40,7 +35,6 @@ public void run() { createAndShowGUI(); } }); - } private static class MathWindowListener implements WindowListener{ @@ -83,14 +77,16 @@ public void windowClosing(WindowEvent arg0) { System.err.println(x); } - try { - if(mg.getMySQLAccess().getConnection().getWarnings() == null) { - mg.getMySQLAccess().connect(); + if(!MathGame.getTypeManager().isOffline()){ + try { + if(MathGame.getMySQLAccess().getConnection().getWarnings() == null) { + MathGame.getMySQLAccess().connect(); + } + MathGame.getMySQLAccess().removeUser(); + GameManager.getMatchesAccess().removeGame(); + } catch (Exception e) { + e.printStackTrace(); } - mg.getMySQLAccess().removeUser(); - GameManager.getMatchesAccess().removeGame(); - } catch (Exception e) { - e.printStackTrace(); } } diff --git a/src/com/mathgame/menus/HostMenu.java b/src/com/mathgame/menus/HostMenu.java index b01bd4f..e57688b 100644 --- a/src/com/mathgame/menus/HostMenu.java +++ b/src/com/mathgame/menus/HostMenu.java @@ -2,7 +2,12 @@ import javax.swing.*; +import com.mathgame.guicomponents.GameButton; +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.MathGame; +import com.mathgame.math.TypeManager; +import com.mathgame.math.TypeManager.Difficulty; +import com.mathgame.math.TypeManager.GameType; import com.mathgame.network.Game; import com.mathgame.network.GameManager; @@ -10,6 +15,7 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; +import java.util.EnumSet; import java.util.HashMap; import java.util.Map; @@ -22,125 +28,83 @@ */ public class HostMenu extends JPanel implements ActionListener { - //TODO Link variables from menu to other variables (i.e. difficulty & number type variables) - //TODO Work on actions to put choice into var //TODO Get user input for name of game & create the location to do that private static final long serialVersionUID = -5507870440809320516L; - static MathGame mathGame; - MultiMenu multiMenu; + private MultiMenu multiMenu; - int players; // # of players (currently 2) - int rounds; // # of rounds (1-5) - String type; // number type (Fraction, Decimal, Integer) - String scoring; // scoring (Complexity, Speed, Mix) - String diff; // difficulty (easy, Medium, HARD) - - static final int BUTTON_WIDTH = 130; - static final int BUTTON_HEIGHT = 30; - - static final String BACKGROUND_FILE = "/images/background2.png"; - static final String BUTTON_IMAGE_FILE = "/images/MenuButtonImg1.png"; - static final String BUTTON_ROLLOVER_IMAGE_FILE = "/images/MenuButtonImg2.png"; - static final String BUTTON_PRESSED_IMAGE_FILE = "/images/MenuButtonImg3.png"; + private int players; // # of players (currently 2) + private int rounds; // # of rounds (1-5) + //private String type; // number type (Fraction, Decimal, Integer) + private String scoring; // scoring (Complexity, Speed, Mix) + private String diff; // difficulty (easy, Medium, HARD) - static ImageIcon background; - static ImageIcon buttonImage; - static ImageIcon buttonRollOverImage; - static ImageIcon buttonPressedImage; + private static final String BACKGROUND_FILE = "/images/background2.png"; - private static final Font eurostile24 = new Font("Eurostile", Font.PLAIN, 24); + private static ImageIcon background; static { - // Image initialization - background = new ImageIcon(OptionMenu.class.getResource(BACKGROUND_FILE)); - buttonImage = new ImageIcon(OptionMenu.class.getResource(BUTTON_IMAGE_FILE)); - buttonRollOverImage = new ImageIcon(OptionMenu.class.getResource(BUTTON_ROLLOVER_IMAGE_FILE)); - buttonPressedImage = new ImageIcon(OptionMenu.class.getResource(BUTTON_PRESSED_IMAGE_FILE)); + background = new ImageIcon(HostMenu.class.getResource(BACKGROUND_FILE)); } - ButtonGroup diffGroup; // Easy, Medium, Hard - ButtonGroup scoringGroup; // Complexity, Speed, Mix - ArrayList types; // Integer, Decimal, Fraction (To be added: Negative, Exponents, Log) - ArrayList diffs; - ArrayList scorings; + private ButtonGroup diffGroup; // Easy, Medium, Hard + private ButtonGroup scoringGroup; // Complexity, Speed, Mix + private ArrayList types; // Integer, Decimal, Fraction (To be added: Negative, Exponents, Log) + private ArrayList diffs; + private ArrayList scorings; - //TODO Make these strings in MathGame class for use in all classes - String[] typeNames = {"Integer", "Decimal", "Fraction"}; - String[] diffNames = {"Easy", "Medium", "Hard"}; - String[] scoringNames = {"Complexity", "Speed", "Mix"}; // Mixed scoring is a combination of speed and complexity + private JSpinner roundsSpinner; // Displaying number of rounds + // private JSpinner playersSpinner; // Displaying number of players + private SpinnerNumberModel roundsModel; + private SpinnerNumberModel playersModel; - JSpinner roundsSpinner; // Displaying number of rounds - // JSpinner playersSpinner; // Displaying number of players - SpinnerNumberModel roundsModel; - SpinnerNumberModel playersModel; - - Map buttonMap; // Associate buttons with their names for easy locating + private Map buttonMap; // Associate buttons with their names for easy locating // JPanel playerPanel; - JPanel scoringPanel; - JPanel roundPanel; - JPanel typePanel; - JPanel diffPanel; + private JPanel scoringPanel; + private JPanel roundPanel; + private JPanel typePanel; + private JPanel diffPanel; + + // private JLabel playersLabel; + private JLabel scoringLabel; + private JLabel typeLabel; + private JLabel roundLabel; + private JLabel diffLabel; - JLabel playersLabel; - JLabel scoringLabel; - JLabel typeLabel; - JLabel roundLabel; - JLabel diffLabel; + private GameButton cancel; + private GameButton finish; - JButton cancel; - JButton finish; + private GridBagConstraints gbc; - GridBagConstraints gbc; + public static Thread waitForPlayer; - public HostMenu(MathGame mg) { + public HostMenu() { this.setLayout(new GridBagLayout()); - mathGame = mg; - multiMenu = (MultiMenu)(mathGame.getMenu(MathGame.Menu.MULTIMENU)); + multiMenu = (MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU)); //TODO Use typemanager? // Set size Dimension size = getPreferredSize(); - size.width = mathGame.getWidth(); - size.height = mathGame.getHeight(); + size.width = MathGame.getAppWidth(); + size.height = MathGame.getAppHeight(); setPreferredSize(size); gbc = new GridBagConstraints(); - playersLabel = new JLabel("# Players:"); + // playersLabel = new JLabel("# Players:"); scoringLabel = new JLabel("Scoring:"); typeLabel = new JLabel("Number Type:"); roundLabel = new JLabel("# Rounds:"); diffLabel = new JLabel("Difficulty:"); - finish = new JButton("Finish"); - finish.setFont(eurostile24); - finish.setHorizontalTextPosition(JButton.CENTER); - finish.setVerticalTextPosition(JButton.CENTER); - finish.setBorderPainted(false); - finish.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT)); + finish = new GameButton("Finish"); finish.addActionListener(this); - cancel = new JButton("Cancel"); - cancel.setFont(eurostile24); - cancel.setHorizontalTextPosition(JButton.CENTER); - cancel.setVerticalTextPosition(JButton.CENTER); - cancel.setBorderPainted(false); - cancel.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT)); + + cancel = new GameButton("Cancel"); cancel.addActionListener(this); - - try { - finish.setIcon(buttonImage); - finish.setRolloverIcon(buttonRollOverImage); - finish.setPressedIcon(buttonPressedImage); - cancel.setIcon(buttonImage); - cancel.setRolloverIcon(buttonRollOverImage); - cancel.setPressedIcon(buttonPressedImage); - } catch (Exception ex) { - ex.printStackTrace(); - } // Button creation buttonMap = new HashMap(); @@ -151,23 +115,24 @@ public HostMenu(MathGame mg) { initRoundPanel(); initScoringPanel(); - gbc.gridx = 0; - gbc.gridy = 0; + // gbc.gridx = 0; + // gbc.gridy = 0; // add(playerPanel, gbc); + gbc.insets = new Insets(5, 5, 5, 5); gbc.gridx = 0; - gbc.gridy = 1; + gbc.gridy = 0; add(typePanel, gbc); - gbc.gridx = 0; - gbc.gridy = 2; - add(diffPanel, gbc); gbc.gridx = 1; gbc.gridy = 0; - add(roundPanel, gbc); + add(diffPanel, gbc); + gbc.gridx = 2; + gbc.gridy = 0; + add(scoringPanel, gbc); gbc.gridx = 1; gbc.gridy = 1; - add(scoringPanel, gbc); + add(roundPanel, gbc); - gbc.gridx = 1; + gbc.gridx = 0; gbc.gridy = 2; add(finish, gbc); gbc.gridx = 2; @@ -185,9 +150,9 @@ public HostMenu(MathGame mg) { playerPanel = new JPanel(); playersModel = new SpinnerNumberModel(2, 2, 6, 1); // 2 to 6 players, default 2 playersSpinner = new JSpinner(playersModel); - playersSpinner.setFont(eurostile24); + playersSpinner.setFont(MathGame.eurostile24); playersLabel = new JLabel("# Players:"); - playersLabel.setFont(eurostile24); + playersLabel.setFont(MathGame.eurostile24); playerPanel.add(playersLabel); playerPanel.add(playersSpinner); }*/ @@ -197,19 +162,22 @@ public HostMenu(MathGame mg) { */ private void initTypePanel() { types = new ArrayList(); - for(String s : typeNames) { - types.add(new JCheckBox(s)); + for(GameType s : TypeManager.GameType.values()) { + types.add(new JCheckBox(s.gameTypeString)); } typePanel = new JPanel(); typeLabel = new JLabel("Number Type:"); - typeLabel.setFont(eurostile24); + typeLabel.setFont(MathGame.eurostile36); + typeLabel.setForeground(MathGame.offWhite); typePanel.setLayout(new BoxLayout(typePanel, BoxLayout.PAGE_AXIS)); typePanel.add(typeLabel); typePanel.setOpaque(false); for(int i = 0; i < types.size(); i++) { + types.get(i).setFont(MathGame.eurostile24); + types.get(i).setForeground(MathGame.offWhite); typePanel.add(types.get(i)); - buttonMap.put(typeNames[i], types.get(i)); - types.get(i).setActionCommand(typeNames[i]); + buttonMap.put(TypeManager.GameType.values()[i].gameTypeString, types.get(i)); + types.get(i).setActionCommand(TypeManager.GameType.values()[i].gameTypeString); types.get(i).setOpaque(false); // types.get(i).addActionListener(this); } @@ -220,21 +188,24 @@ private void initTypePanel() { */ private void initDiffPanel() { diffs = new ArrayList(); - for(String s : diffNames) { - diffs.add(new JRadioButton(s)); + for(TypeManager.Difficulty s : TypeManager.Difficulty.values()) { + diffs.add(new JRadioButton(s.difficultyString)); } diffPanel = new JPanel(); diffGroup = new ButtonGroup(); diffLabel = new JLabel("Difficulty:"); - diffLabel.setFont(eurostile24);; + diffLabel.setFont(MathGame.eurostile36); + diffLabel.setForeground(MathGame.offWhite); diffPanel.setLayout(new BoxLayout(diffPanel, BoxLayout.PAGE_AXIS)); diffPanel.add(diffLabel); diffPanel.setOpaque(false); for(int i = 0; i < diffs.size(); i++) { + diffs.get(i).setFont(MathGame.eurostile24); + diffs.get(i).setForeground(MathGame.offWhite); diffGroup.add(diffs.get(i)); diffPanel.add(diffs.get(i)); - buttonMap.put(diffNames[i], diffs.get(i)); - diffs.get(i).setActionCommand(diffNames[i]); + buttonMap.put(TypeManager.Difficulty.values()[i].difficultyString, diffs.get(i)); + diffs.get(i).setActionCommand(TypeManager.Difficulty.values()[i].difficultyString); diffs.get(i).setOpaque(false); // diffs.get(i).addActionListener(this); } @@ -248,9 +219,9 @@ private void initRoundPanel() { // Choose from 1 to 5 rounds, with a default of 3 rounds roundsModel = new SpinnerNumberModel(3, 1, 5, 1); roundsSpinner = new JSpinner(roundsModel); - roundsSpinner.setFont(eurostile24); + roundsSpinner.setFont(MathGame.eurostile36); roundLabel = new JLabel("# Rounds:"); - roundLabel.setFont(eurostile24); + roundLabel.setFont(MathGame.eurostile36); roundPanel.add(roundLabel); roundPanel.add(roundsSpinner); } @@ -260,21 +231,24 @@ private void initRoundPanel() { */ private void initScoringPanel() { scorings = new ArrayList(); - for(String s : scoringNames) { + for(String s : MathGame.scorings) { scorings.add(new JRadioButton(s)); } scoringPanel = new JPanel(); scoringGroup = new ButtonGroup(); scoringPanel.setLayout(new BoxLayout(scoringPanel, BoxLayout.PAGE_AXIS)); scoringLabel = new JLabel("Scoring:"); - scoringLabel.setFont(eurostile24); + scoringLabel.setFont(MathGame.eurostile36); + scoringLabel.setForeground(MathGame.offWhite); scoringPanel.add(scoringLabel); scoringPanel.setOpaque(false); for(int i = 0; i < scorings.size(); i++) { + scorings.get(i).setFont(MathGame.eurostile24); + scorings.get(i).setForeground(MathGame.offWhite); scoringGroup.add(scorings.get(i)); scoringPanel.add(scorings.get(i)); - buttonMap.put(scoringNames[i], scorings.get(i)); - scorings.get(i).setActionCommand(scoringNames[i]); + buttonMap.put(MathGame.scorings[i], scorings.get(i)); + scorings.get(i).setActionCommand(MathGame.scorings[i]); scorings.get(i).setOpaque(false); // scorings.get(i).addActionListener(this); } @@ -282,61 +256,133 @@ private void initScoringPanel() { public void actionPerformed(ActionEvent e) { if(e.getSource() == finish) { - addGame(); - mathGame.getCardPanel().hideCards(); // Hide cards until next player joins - mathGame.showMenu(MathGame.Menu.GAME); // Go to the game (but should it wait?) - Thread waitForPlayer = new Thread() { - public void run() { - while(!mathGame.getGameManager().gameFilled()) { - System.out.println("waiting"); // Wait until the game is filled - } - mathGame.getCardPanel().showCards(); - mathGame.getSidePanel().startTimer(type); - mathGame.getSidePanel().setUpMultiplayer(); - mathGame.getGameManager(); - - //Get the names of the other players - int numPlayers = mathGame.getGameManager().getGame().getNumberOfPlayers(); - for(int i=1; i<=numPlayers; i++) - { - mathGame.getGameManager().getGame().addPlayer(GameManager.getMatchesAccess().getPlayerName(mathGame.getGameManager().getGame().getID(), i)); - } + //check to make sure at least 1 checkbox is selected for game type + boolean noSelected = true; + for(JCheckBox cb : types) { + if(cb.isSelected()) { + noSelected = false; + break; + } + } + if(noSelected) { + GameDialogFactory.showGameMessageDialog(this, "Error", "Please select a game type.", GameDialogFactory.OK); + } else { + System.out.println("GAMESTATE: "+ MathGame.getGameState()); + if(MathGame.getGameState() == MathGame.GameState.PRACTICE) + try { + startPractice(); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); } - }; - waitForPlayer.start(); - mathGame.getUser().setPlayerID(1); + else if(MathGame.getGameState() == MathGame.GameState.COMPETITIVE) + try { + startMultiplayer(); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } } else if(e.getSource() == cancel) { - mathGame.showMenu(MathGame.Menu.MULTIMENU); // Return to the multiplayer menu + MathGame.showMenu(MathGame.Menu.MULTIMENU); // Return to the multiplayer menu + } + } + + /** + * Changes layout for practice + */ + public void configurePractice() { + roundPanel.setVisible(false); + } + + /** + * Changes layout for multiplayer + */ + public void configureMultiplayer() { + roundPanel.setVisible(true); + } + + /** + * Sets the Type of game and difficulty chosen by user into typemanager + */ + private void setGameType() { + /*type = TypeManager.GameType.INTEGERS.gameTypeString; + MathGame.getTypeManager().setType(GameType.INTEGERS);//default, otherwise change below + MathGame.getTypeManager().setDiff(Difficulty.EASY);//default, otherwise change below*/ + MathGame.getTypeManager().clearType(); + for(GameType g : GameType.values()) { + if(buttonMap.get(g.gameTypeString).isSelected()) { + MathGame.getTypeManager().addType(g); + } } + diff = diffGroup.getSelection().getActionCommand(); + scoring = scoringGroup.getSelection().getActionCommand(); + MathGame.getTypeManager().setDiff(diff); + } + + /** + * Starts a practice game (single player) + * @throws Exception + */ + private void startPractice() throws Exception { + setGameType(); + MathGame.getTypeManager().randomize(); + System.out.println("ENTER GAME"); + MathGame.showMenu(MathGame.Menu.GAME); + MathGame.getSidePanel().startTimer(scoring); + } + + /** + * Starts a multiplayer game + * @throws Exception + */ + private void startMultiplayer() throws Exception { + addGame(); + MathGame.getCardPanel().hideCards(); // Hide cards until next player joins + System.out.println("ENTER GAME"); + MathGame.showMenu(MathGame.Menu.GAME); // Go to the game (but should it wait?) + waitForPlayer = new Thread() { + public void run() { + while(!MathGame.getGameManager().gameFilled()) { + System.out.println("waiting"); // Wait until the game is filled + System.out.println("Cnct?1 :" + MathGame.dbConnected); + if(MathGame.dbConnected == false) + { + this.interrupt(); + break; + } + } + if(this.isInterrupted()) + return; + MathGame.getCardPanel().showCards(); + MathGame.getSidePanel().startTimer(scoring); + MathGame.getSidePanel().setUpMultiplayer(); + + //Get the names of the other players + int numPlayers = MathGame.getGameManager().getGame().getNumberOfPlayers(); + for(int i=1; i<=numPlayers; i++) + { + MathGame.getGameManager().getGame().addPlayer(GameManager.getMatchesAccess().getPlayerName(MathGame.getGameManager().getGame().getID(), i)); + } + } + + }; + waitForPlayer.start(); + MathGame.getUser().setPlayerID(1); } /** * Adds a new game + * @throws Exception */ - public void addGame() { + public void addGame() throws Exception { this.setVisible(false); // players = (Integer) playersSpinner.getModel().getValue(); players = 2; rounds = (Integer) roundsSpinner.getModel().getValue(); - diff = diffGroup.getSelection().getActionCommand(); - scoring = scoringGroup.getSelection().getActionCommand(); - - //TODO Set capability for multiple (instead of first one picked) - if(buttonMap.get("Integer").isSelected()) { - multiMenu.chooseInteger(); - type = "Integer"; - } else if(buttonMap.get("Decimal").isSelected()) { - multiMenu.chooseDecimal(); - type = "Decimal"; - } else if(buttonMap.get("Fraction").isSelected()) { - multiMenu.chooseFraction(); - type = "Fraction"; - } else { - // The default game type is "Integer" (for now) - multiMenu.chooseInteger(); - type = "Integer"; - } + + setGameType(); // Etc. System.out.println("MULTIPLAYER GAME SPECS: " @@ -344,15 +390,14 @@ public void addGame() { + "\n\tROUNDS: "+rounds + "\n\tDIFF: "+diff + "\n\tSCORING: "+scoring - + "\n\tTYPE: "+type + + "\n\tTYPE: "+MathGame.getTypeManager().getType().toString() + "\n\tNUMPLAYERS: "+players); - multiMenu.addGame(new Game(-1, players, type, scoring, diff, rounds)); + multiMenu.addGame(new Game(-1, players, MathGame.getTypeManager().getType().toString(), scoring, diff, rounds)); - mathGame.getTypeManager().setType(type); - mathGame.getTypeManager().randomize(); + MathGame.getTypeManager().randomize(); // FOR DEBUGGING PURPOSES ONLY: - mathGame.showMenu(MathGame.Menu.MULTIMENU); + //MathGame.showMenu(MathGame.Menu.MULTIMENU); //TODO Go directly to game and make sure game waits for another player System.out.println("CREATED NEW GAME"); } diff --git a/src/com/mathgame/menus/LoginMenu.java b/src/com/mathgame/menus/LoginMenu.java new file mode 100644 index 0000000..6c5c46e --- /dev/null +++ b/src/com/mathgame/menus/LoginMenu.java @@ -0,0 +1,155 @@ +/** + * + */ +package com.mathgame.menus; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; + +import com.mathgame.guicomponents.GameButton; +import com.mathgame.guicomponents.GameDialogFactory; +import com.mathgame.math.MathGame; +import com.mathgame.math.SoundManager; +import com.mathgame.network.GameManager; + +/** + * The LoginMenu class represents the menu that lets players log in when the game is opened + * @author Roland, Noah + */ +public class LoginMenu extends JPanel implements ActionListener { + + private static final long serialVersionUID = 7263913541929112166L; + + private JLabel usernameLabel; + private JLabel passwordLabel; + private JTextField usernameField; + private JPasswordField passwordField; + private GameButton login; + private GameButton register; + public static GameButton connectAgain; + + private static final String IMAGE_FILE = "/images/backa.png"; + + private static ImageIcon background = new ImageIcon(LoginMenu.class.getResource(IMAGE_FILE)); + + public LoginMenu() { + setLayout(null); + + usernameLabel = new JLabel("Username:"); + usernameLabel.setFont(MathGame.eurostile24); + usernameLabel.setForeground(MathGame.offWhite); + usernameLabel.setBounds(320, 350, 110, 30); + + passwordLabel = new JLabel("Password:"); + passwordLabel.setFont(MathGame.eurostile24); + passwordLabel.setForeground(MathGame.offWhite); + passwordLabel.setBounds(320, 390, 110, 30); + + + usernameField = new JTextField(); + usernameField.setFont(MathGame.eurostile24); + usernameField.setBounds(440, 350, 150, 30); + usernameField.addActionListener(this); + + passwordField = new JPasswordField(); + passwordField.setFont(MathGame.eurostile24); + passwordField.setBounds(440, 390, 150, 30); + passwordField.addActionListener(this); + + login = new GameButton("Log In"); + login.setLocation(400, 440); + login.addActionListener(this); + + register = new GameButton("Register"); + register.setLocation(400, 500); + register.addActionListener(this); + + + connectAgain = new GameButton("Connect again?"); + connectAgain.setLocation(400, 300); + connectAgain.addActionListener(this); + connectAgain.setVisible(false); + + + + this.add(usernameLabel); + //while(MathGame.dbBackgroundConnectDone == false) + // ; + + + this.add(usernameLabel); + this.add(passwordLabel); + this.add(usernameField); + this.add(passwordField); + this.add(login); + this.add(register); + this.add(connectAgain); + + + + System.out.println("Login menu init complete"); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() instanceof JButton) { + SoundManager.playSound(SoundManager.SoundType.BUTTON); + } + //click login button or press enter inside the username/password fields + if(e.getSource() == login || e.getSource() == usernameField || e.getSource() == passwordField) { + if(usernameField.getText().equals("") || passwordField.getPassword().length == 0) { + //JOptionPane.showMessageDialog(this, "Please Enter a Username and Password"); + GameDialogFactory.showGameMessageDialog(this, "Error", "Please Enter a Username and Password", GameDialogFactory.OK); + } + else { + System.out.println("user name is " + usernameField.getText()); + String u = usernameField.getText(); + char[] p = passwordField.getPassword(); + + if(MathGame.getMySQLAccess().loginUser(u, p) == false) + { + if(MathGame.dbConnected == false) + { + connectAgain.setVisible(true); + } + else//Username/pass are wrong + { + GameDialogFactory.showGameMessageDialog(this, "Error", "Wrong username or password", GameDialogFactory.OK); + System.out.println("Invalid username or password"); + } + return; + } + MathGame.getUser().setName(usernameField.getText()); + MathGame.getUser().setPassword(passwordField.getPassword().toString()); + ((MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU))).refreshDatabase(); + ((MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU))).addThisUser(); + MathGame.showMenu(MathGame.Menu.MAINMENU); + } + } else if(e.getSource() == register){ + MathGame.showMenu(MathGame.Menu.REGISTER); + } else if(e.getSource() == connectAgain){ + if(MathGame.getMySQLAccess().displayUserConnectAgain()) + MathGame.backgroundInit(); + + } + + } + + @Override + public void paintComponent(Graphics g){ + super.paintComponents(g); + g.drawImage(background.getImage(), 0, 0, LoginMenu.this); + } + +} diff --git a/src/com/mathgame/menus/MainMenu.java b/src/com/mathgame/menus/MainMenu.java index 5cf98a0..9635188 100644 --- a/src/com/mathgame/menus/MainMenu.java +++ b/src/com/mathgame/menus/MainMenu.java @@ -8,13 +8,15 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; +import java.lang.*; +import java.util.concurrent.TimeUnit; import javax.swing.ImageIcon; import javax.swing.JButton; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; +import com.mathgame.guicomponents.GameButton; import com.mathgame.math.MathGame; import com.mathgame.math.SoundManager; @@ -28,39 +30,31 @@ public class MainMenu extends JPanel implements ActionListener, MouseMotionListe private static final long serialVersionUID = -3036828086937465893L; - MathGame mathGame; + private static final String IMAGE_FILE = "/images/backb.png"; - static final String IMAGE_FILE = "/images/backa.png"; - static final String BUTTON_IMAGE_FILE = "/images/MenuButtonImg1.png"; - static final String BUTTON_ROLLOVER_IMAGE_FILE = "/images/MenuButtonImg2.png"; - static final String BUTTON_PRESSED_IMAGE_FILE = "/images/MenuButtonImg3.png"; - static final int BUTTON_WIDTH = 130; - static final int BUTTON_HEIGHT = 30; - ImageIcon background; - ImageIcon buttonImage; - ImageIcon buttonRollOverImage; - ImageIcon buttonPressedImage; + private ImageIcon background; // Mouse coordinates - int mx; - int my; + private int mx; + private int my; - JButton enter; // Press to enter the game; - JButton help; // Press for game help - JButton about; // Press for "stuff" - JButton exit; // Press to leave game :( + private GameButton enter; // Press to enter the game; + private GameButton help; // Press for game help + private GameButton about; // Press for "stuff" + private GameButton exit; // Press to leave game :( + private JButton sound; // Press to mute/unmute // JLabel epsilon; // Self-explanatory - JPanel carda; - JPanel cardb; - JPanel cardc; - JPanel cardd; - JTextArea infoa; - JTextArea infob; - JTextArea infoc; - JTextArea infod; + private JPanel carda; + private JPanel cardb; + private JPanel cardc; + private JPanel cardd; + private JTextArea infoa; + private JTextArea infob; + private JTextArea infoc; + private JTextArea infod; - public void init(MathGame mg) { + public void init() { this.setLayout(null); Dimension size = getPreferredSize(); @@ -68,67 +62,32 @@ public void init(MathGame mg) { size.height = 620; setPreferredSize(size); - mathGame = mg; - - background = new ImageIcon(MainMenu.class.getResource(IMAGE_FILE)); - buttonImage = new ImageIcon(MainMenu.class.getResource(BUTTON_IMAGE_FILE)); - buttonRollOverImage = new ImageIcon(MainMenu.class.getResource(BUTTON_ROLLOVER_IMAGE_FILE)); - buttonPressedImage = new ImageIcon(MainMenu.class.getResource(BUTTON_PRESSED_IMAGE_FILE)); background = new ImageIcon(MainMenu.class.getResource(IMAGE_FILE)); - - // Font titleFont = new Font("Arial", Font.BOLD, 36); - Font buttonFont = new Font("Arial", Font.PLAIN, 20); Font infoFont = new Font("Arial", Font.BOLD, 12); - // epsilon = new JLabel("Epsilon"); - // epsilon.setFont(titleFont); - // epsilon.setBounds(185, 205, 130, 60); - - enter = new JButton("Enter"); - enter.setFont(buttonFont); - enter.setBounds(105, 335, BUTTON_WIDTH, BUTTON_HEIGHT); - enter.setHorizontalTextPosition(JButton.CENTER); - enter.setVerticalTextPosition(JButton.CENTER); - enter.setBorderPainted(false); + enter = new GameButton("Enter"); + enter.setLocation(105, 335); - help = new JButton("Help"); - help.setFont(buttonFont); - help.setBounds(295, 335, BUTTON_WIDTH, BUTTON_HEIGHT); - help.setHorizontalTextPosition(JButton.CENTER); - help.setVerticalTextPosition(JButton.CENTER); - help.setBorderPainted(false); + help = new GameButton("Help"); + help.setLocation(295, 335); - about = new JButton("About"); - about.setFont(buttonFont); - about.setBounds(490, 335, BUTTON_WIDTH, BUTTON_HEIGHT); - about.setHorizontalTextPosition(JButton.CENTER); - about.setVerticalTextPosition(JButton.CENTER); - about.setBorderPainted(false); + about = new GameButton("About"); + about.setLocation(490, 335); - exit = new JButton("Exit"); - exit.setFont(buttonFont); - exit.setBounds(672, 335, BUTTON_WIDTH, BUTTON_HEIGHT); - exit.setHorizontalTextPosition(JButton.CENTER); - exit.setVerticalTextPosition(JButton.CENTER); - exit.setBorderPainted(false); - - try { - enter.setIcon(buttonImage); - enter.setRolloverIcon(buttonRollOverImage); - enter.setPressedIcon(buttonPressedImage); - help.setIcon(buttonImage); - help.setRolloverIcon(buttonRollOverImage); - help.setPressedIcon(buttonRollOverImage); - about.setIcon(buttonImage); - about.setRolloverIcon(buttonRollOverImage); - about.setPressedIcon(buttonRollOverImage); - exit.setIcon(buttonImage); - exit.setRolloverIcon(buttonRollOverImage); - exit.setPressedIcon(buttonPressedImage); + exit = new GameButton("Exit"); + exit.setLocation(672, 335); + + sound = new JButton(); + sound.setBounds(15, 15, SoundManager.currentVolumeButtonImage().getIconWidth(), SoundManager.currentVolumeButtonImage().getIconHeight()); + sound.setBorderPainted(true); + + try { + sound.setIcon(SoundManager.currentVolumeButtonImage()); } catch (Exception ex) { ex.printStackTrace(); } + //TODO Get the text in the label to wrap if it is longer than the label width. // Info Box for Enter Box @@ -189,6 +148,7 @@ public void init(MathGame mg) { add(help); add(about); add(exit); + add(sound); add(carda); add(cardb); @@ -209,38 +169,44 @@ public void init(MathGame mg) { exit.addActionListener(this); exit.addMouseMotionListener(this); exit.addMouseListener(this); + sound.addActionListener(this); // get username before playing - getUser(); + //getUser();//superseded by login menu - System.out.println("Menu Init Complete"); - } - - /** - * Prompts the user for their username - */ - public void getUser() { - String name = JOptionPane.showInputDialog(this, "User Name"); - System.out.println("user name is " + name); - mathGame.getUser().setName(name); + System.out.println("MainMenu Init Complete"); } public void actionPerformed(ActionEvent e) { - if (e.getSource() instanceof JButton) { + if (e.getSource() instanceof GameButton) { SoundManager.playSound(SoundManager.SoundType.BUTTON); } - if(e.getSource() == enter) { + if (e.getSource() == enter) { + + /* + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + }*/ startGame(); + SoundManager.playSound(SoundManager.SoundType.WAIT); + System.out.println("Looping wait music"); } // else if(e.getSource() == help) // helpbox(); // else if(e.getSource() == about) // aboutinfo(); - else if(e.getSource() == exit) { + else if (e.getSource() == exit) { exit(); } + + else if (e.getSource() == sound) { + sound.setIcon(SoundManager.volumeButtonPressed()); + } } /** @@ -269,8 +235,11 @@ else if(n == 2) mathGame.multimenu.addThisUser(); } //mathGame.cl.show(mathGame.cardLayoutPanels, mathGame.SUBMENU);*/ - - mathGame.showMenu(MathGame.Menu.OPTIONMENU); + if(!MathGame.getTypeManager().isOffline()) { + ((MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU))).refreshDatabase(); + ((MultiMenu)(MathGame.getMenu(MathGame.Menu.MULTIMENU))).refreshTimer.start(); + } + MathGame.showMenu(MathGame.Menu.MULTIMENU); System.out.println("ENTER GAME"); } @@ -335,7 +304,8 @@ public void exitinfo() { */ public void exit() { //TODO Decide on exit implementation (perhaps show an html webpage "thanks for playing")? - JOptionPane.showMessageDialog(this, "Game cannot exit from this button yet. Please use the x button @ top right", null, JOptionPane.WARNING_MESSAGE, null); + //Perhaps turn this into a Log-off button? + //JOptionPane.showMessageDialog(this, "Game cannot exit from this button yet. Please use the x button @ top right", null, JOptionPane.WARNING_MESSAGE, null); } @Override @@ -381,7 +351,7 @@ public void mouseEntered(MouseEvent e) { @Override public void mouseExited(MouseEvent e) { - System.out.println("Mouse Exited Button"); + //System.out.println("Mouse Exited Button"); hideInfo(); if(e.getSource() == help) { // info.setText("Welcome to Epsilon, the mathematical card game!"); diff --git a/src/com/mathgame/menus/MultiMenu.java b/src/com/mathgame/menus/MultiMenu.java index e78f583..f4e7719 100644 --- a/src/com/mathgame/menus/MultiMenu.java +++ b/src/com/mathgame/menus/MultiMenu.java @@ -3,11 +3,8 @@ import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; -import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; -import java.awt.GridLayout; -import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; @@ -19,17 +16,17 @@ import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; -import javax.swing.JOptionPane; import javax.swing.JPanel; -// import javax.swing.Timer; - - - +import javax.swing.JTextArea; +import javax.swing.Timer; +import javax.swing.border.TitledBorder; +import com.mathgame.guicomponents.GameButton; +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.MathGame; import com.mathgame.math.SoundManager; import com.mathgame.math.TypeManager; -import com.mathgame.math.TypeManager.Difficulty; +import com.mathgame.math.MathGame.GameState; import com.mathgame.network.Game; import com.mathgame.network.GameManager; import com.mathgame.network.User; @@ -42,60 +39,36 @@ public class MultiMenu extends JPanel implements ActionListener, MouseMotionList private static final long serialVersionUID = -3036828086937465893L; - static MathGame mathGame; TypeManager typeManager; - static final String IMAGE_FILE = "/images/backMulti.png"; - static final String BUTTON_IMAGE_FILE = "/images/buttonStandard.png"; - static final String BUTTON_ROLLOVER_IMAGE_FILE = "/images/buttonRollover.png"; - static final String BUTTON_PRESSED_IMAGE_FILE = "/images/buttonStandard.png"; - static final String REFRESH_BUTTON_IMAGE_FILE = "/images/refreshButton.png"; // - static final String REFRESH_BUTTON_ROLLOVER_IMAGE_FILE = "/images/refresnButtonRollover.png"; // + private static final String IMAGE_FILE = "/images/backMulti.png"; - static final int BUTTON_WIDTH = 130; - static final int BUTTON_HEIGHT = 30; - static final int WIDE_BUTTON_WIDTH = 150; - - static ImageIcon background; - static ImageIcon buttonImage; - static ImageIcon buttonRollOverImage; - static ImageIcon buttonPressedImage; - static ImageIcon refreshButton; // the refresh button is 150 pixels wide, while the others are 130 - static ImageIcon refreshButtonRollover; - - static { - background = new ImageIcon(MultiMenu.class.getResource(IMAGE_FILE)); - buttonImage = new ImageIcon(MultiMenu.class.getResource(BUTTON_IMAGE_FILE)); - buttonRollOverImage = new ImageIcon(MultiMenu.class.getResource(BUTTON_ROLLOVER_IMAGE_FILE)); - buttonPressedImage = new ImageIcon(MultiMenu.class.getResource(BUTTON_PRESSED_IMAGE_FILE)); - refreshButton = new ImageIcon(MultiMenu.class.getResource(REFRESH_BUTTON_IMAGE_FILE)); - refreshButtonRollover = new ImageIcon(MultiMenu.class.getResource(REFRESH_BUTTON_ROLLOVER_IMAGE_FILE)); - } + private static ImageIcon background = new ImageIcon(MultiMenu.class.getResource(IMAGE_FILE)); // Mouse coordinates - int mx; - int my; + private int mx; + private int my; - JPanel gamesList; - JPanel usersList; - JButton home; // Press to enter a game; - JButton host; // Press to host a game - JButton join; // Press to join a game - JButton refresh; // Updates from database - JLabel mode; - JLabel friend; + private Font titleFont; - Panel innerPanel; + private JPanel gamesList; + private GameButton home; // Press to enter a game + private GameButton host; // Press to host a game + private GameButton join; // Press to join a game + private GameButton practice; // Press to enter practice mode + private JTextArea usersList; + private JTextArea userProfile; // Displays info about the selected user (win/loss, etc) - final int NUMBEROFPLAYERS = 2;//TOOD: get rid of this + private final int NUMBER_PLAYERS = 2; //TODO Get rid of this - GameManager gameManager; - HostMenu hostMenu; + private GameManager gameManager; private ArrayList usersArray; private ArrayList games; private ArrayList gameCards; - public void init(MathGame mg, TypeManager tn) { + public Timer refreshTimer; + + public void init() { this.setLayout(null); Dimension size = getPreferredSize(); @@ -103,124 +76,80 @@ public void init(MathGame mg, TypeManager tn) { size.height = 620; setPreferredSize(size); - mathGame = mg; - typeManager = tn; - gameManager = mathGame.getGameManager(); - hostMenu = new HostMenu(mathGame); - - Font titleFont = new Font("Arial", Font.BOLD, 24); - Font buttonFont = new Font("Arial", Font.PLAIN, 20); - - mode = new JLabel("Lobby"); - mode.setFont(titleFont); - mode.setBounds(305, 50, 100, 60); + typeManager = MathGame.getTypeManager(); + gameManager = MathGame.getGameManager(); - friend = new JLabel("Online"); - friend.setFont(titleFont); - friend.setBounds(680, 50, 100, 60); + titleFont = MathGame.eurostile24; - home = new JButton("Back"); - home.setFont(buttonFont); - home.setBounds(99, 535, BUTTON_WIDTH, BUTTON_HEIGHT); - home.setHorizontalTextPosition(JButton.CENTER); - home.setVerticalTextPosition(JButton.CENTER); - home.setBorderPainted(false); + home = new GameButton("Back"); + home.setLocation(50, 535); - host = new JButton("Host"); - host.setFont(buttonFont); - host.setBounds(284, 535, BUTTON_WIDTH, BUTTON_HEIGHT); - host.setHorizontalTextPosition(JButton.CENTER); - host.setVerticalTextPosition(JButton.CENTER); - host.setBorderPainted(false); + host = new GameButton("Host"); + host.setLocation(273, 535); - join = new JButton("Join"); - join.setFont(buttonFont); - join.setBounds(469, 535, BUTTON_WIDTH, BUTTON_HEIGHT); - join.setHorizontalTextPosition(JButton.CENTER); - join.setVerticalTextPosition(JButton.CENTER); - join.setBorderPainted(false); + join = new GameButton("Join"); + join.setLocation(496, 535); - refresh = new JButton("Refresh"); - refresh.setFont(buttonFont); - refresh.setBounds(650, 535, WIDE_BUTTON_WIDTH, BUTTON_HEIGHT); - refresh.setHorizontalTextPosition(JButton.CENTER); - refresh.setVerticalTextPosition(JButton.CENTER); - refresh.setBorderPainted(false); + practice = new GameButton("Practice"); + practice.setLocation(720, 535); gamesList = new JPanel(); - gamesList.setBounds(100, 100, 500, 400); - gamesList.setBorder(BorderFactory.createLineBorder(Color.black)); - gamesList.setForeground(Color.black); - gamesList.setBackground(Color.lightGray); + gamesList.setBounds(50, 50, 600, 450); + gamesList.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.GREEN, 2), + "Lobby", TitledBorder.CENTER, TitledBorder.BELOW_TOP, + titleFont, Color.BLACK)); + gamesList.setBackground(Color.WHITE); gamesList.setVisible(true); - usersList = new JPanel(); - usersList.setBounds(650, 100, 150, 400); - usersList.setForeground(Color.black); - usersList.setBackground(Color.lightGray); - usersList.setBorder(BorderFactory.createLineBorder(Color.black)); + usersList = new JTextArea(); + usersList.setBounds(650, 200, 200, 300); + usersList.setBackground(Color.WHITE); + usersList.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.GREEN, 2), + "Users", TitledBorder.CENTER, TitledBorder.BELOW_TOP, + titleFont, Color.BLACK)); + usersList.setEditable(false); usersList.setVisible(true); - GridLayout columnLayout = new GridLayout(0, 1); - innerPanel = new Panel(); - innerPanel.setLayout(new FlowLayout()); - - usersList.setLayout(columnLayout); - usersList.add(innerPanel); + userProfile = new JTextArea(); + userProfile.setBounds(650, 50, 200, 150); + userProfile.setBackground(Color.WHITE); + userProfile.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.GREEN, 2), + "User Profile", TitledBorder.CENTER, TitledBorder.BELOW_TOP, + titleFont, Color.BLACK)); + userProfile.setEditable(false); + userProfile.setVisible(true); usersArray = new ArrayList(); - games = GameManager.getMatchesAccess().getCurrentGames(); - gameCards = new ArrayList(); - - for(Game game : games) { - // For each game, create a gamecard - GameCard gc = new GameCard(game.getID(), "Game "+String.valueOf(game.getID()), NUMBEROFPLAYERS, - game.getType(), game.getScoring(), game.getDiff(), game.getRounds()); - + if(!MathGame.getTypeManager().isOffline()) { + games = GameManager.getMatchesAccess().getCurrentGames(); + gameCards = new ArrayList(); - gameCards.add(gc); - } - - for(GameCard card : gameCards) { - gamesList.add(card); + for(Game game : games) { + // For each game, create a gamecard + GameCard gc = new GameCard(game.getID(), "Game "+String.valueOf(game.getID()), NUMBER_PLAYERS, + game.getType(), game.getScoring(), game.getDiff(), game.getRounds()); + gameCards.add(gc); + } + + for(GameCard card : gameCards) { + gamesList.add(card); + } } - try { - home.setIcon(buttonImage); - home.setRolloverIcon(buttonRollOverImage); - home.setPressedIcon(buttonPressedImage); - - host.setIcon(buttonImage); - host.setRolloverIcon(buttonRollOverImage); - host.setPressedIcon(buttonRollOverImage); - - join.setIcon(buttonImage); - join.setRolloverIcon(buttonRollOverImage); - join.setPressedIcon(buttonRollOverImage); - - refresh.setIcon(refreshButton); - refresh.setRolloverIcon(refreshButtonRollover); - refresh.setPressedIcon(refreshButton); - - } catch (Exception ex) { - ex.printStackTrace(); - } //TODO Get the text in the label to wrap if it is longer than the label width // Info Box for Enter Box - add(mode); - add(friend); add(home); add(host); add(join); - add(refresh); + add(practice); add(gamesList); add(usersList); - - // p1.setBorder(new TitledBorder("Epsilon")); - - // add(epsilon); + add(userProfile); home.addActionListener(this); home.addMouseMotionListener(this); @@ -228,31 +157,31 @@ public void init(MathGame mg, TypeManager tn) { host.addMouseMotionListener(this); host.addMouseListener(this); host.addActionListener(this); + join.addMouseMotionListener(this); join.addMouseListener(this); join.addActionListener(this); - refresh.addActionListener(this); - refresh.addMouseMotionListener(this); - refresh.addMouseListener(this); - // Start refresh thread - /* - Thread refreshThread = new Thread() { - public void run() { - Timer refreshTimer = new Timer(500, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - refresh(); - } - }); - refreshTimer.start(); - } - }; - */ - // refreshThread.start(); //TODO Enable when we get a better refresh algorithm - // I suggest checking database for changes. If there are changes, refresh; otherwise, do nothing. + practice.addActionListener(this); + practice.addMouseMotionListener(this); + practice.addMouseListener(this); + + if(!MathGame.getTypeManager().isOffline()) + startRefreshTimer(); - System.out.println("Menu Init Complete"); + System.out.println("MultiMenu Init Complete"); + } + + public void startRefreshTimer(){ + // Start refresh thread + refreshTimer = new Timer(2000, new ActionListener(){ + @Override + public void actionPerformed(ActionEvent arg0) { + refresh(); + } + }); + refreshTimer.setInitialDelay(0); + //refreshTimer.start(); } public void setGameManager(GameManager gameManager) { @@ -263,20 +192,29 @@ public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { SoundManager.playSound(SoundManager.SoundType.BUTTON); } - //TODO Program functionality of buttons? + if(e.getSource() == home) { - mathGame.showMenu(MathGame.Menu.MAINMENU); // Return to the main menu - // choosefraction(); - // startgame(); + MathGame.showMenu(MathGame.Menu.MAINMENU); // Return to the main menu + if(!MathGame.getTypeManager().isOffline()) + refreshTimer.stop(); } else if(e.getSource() == host) { - mathGame.showMenu(MathGame.Menu.HOSTMENU); - // startgame(); + if(MathGame.getTypeManager().isOffline()) + GameDialogFactory.showGameMessageDialog(this, + "Offline", "Offline mode. Cannot start multiplayer game", + GameDialogFactory.OK); + else { + MathGame.setGameState(GameState.COMPETITIVE); + ((HostMenu)MathGame.getMenu(MathGame.Menu.HOSTMENU)).configureMultiplayer(); + MathGame.showMenu(MathGame.Menu.HOSTMENU); + } } else if(e.getSource() == join) { - // choosedecimal(); - // startgame(); } - else if(e.getSource() == refresh) { - refresh(); + else if(e.getSource() == practice) { + MathGame.setGameState(GameState.PRACTICE); + ((HostMenu)MathGame.getMenu(MathGame.Menu.HOSTMENU)).configurePractice(); + MathGame.showMenu(MathGame.Menu.HOSTMENU);// select practice options + if(!MathGame.getTypeManager().isOffline()) + refreshTimer.stop(); } } @@ -287,16 +225,16 @@ public void refresh() { refreshDatabase(); games = gameManager.getCurrentGames(); + if(games == null) + { + System.err.println("Games from db is null"); + return; + } gameCards.clear(); for(Game game : games) { - GameCard gc = new GameCard(game.getID(), "Game "+String.valueOf(game.getID()), NUMBEROFPLAYERS, + GameCard gc = new GameCard(game.getID(), "Game "+String.valueOf(game.getID()), NUMBER_PLAYERS, game.getType(), game.getScoring(), game.getDiff(), game.getRounds()); - //TODO For demonstration purposes only (reducing clutter); delete the if statement - if(game.getID() < 159) { - //TODO DELETE - gc.setVisible(false); - } gameCards.add(gc); } gamesList.removeAll(); @@ -325,7 +263,7 @@ public void addGame(Game g) { int gameID = gameManager.hostGame(); // Needed so the game manager knows what game it's managing g.setID(gameID); games.add(g); - gameCards.add(new GameCard(gameID, "Game "+gameID, NUMBEROFPLAYERS, + gameCards.add(new GameCard(gameID, "Game "+gameID, NUMBER_PLAYERS, g.getType(), g.getScoring(), g.getDiff(), g.getRounds())); gamesList.add(gameCards.get(games.size() - 1)); GameManager.getMatchesAccess().setMatchNum(gameID); @@ -340,11 +278,10 @@ public void addGame(Game g) { /** * Add the current user to the list of users */ - public void addThisUser(){ - try { - if(mathGame.getMySQLAccess().getConnection() == null) - mathGame.getMySQLAccess().connect(); - mathGame.getMySQLAccess().addUser(); + public void addThisUser(){ try { + if(MathGame.getMySQLAccess().getConnection() == null) + MathGame.getMySQLAccess().connect(); + MathGame.getMySQLAccess().addUser(); // mathGame.sql.close(); } catch (Exception e) { // TODO Auto-generated catch block @@ -357,10 +294,12 @@ public void addThisUser(){ */ public void refreshDatabase() { try { - if (mathGame.getMySQLAccess().getConnection() == null) { - mathGame.getMySQLAccess().connect(); + if (MathGame.getMySQLAccess().getConnection() == null) { + return; } - usersArray = mathGame.getMySQLAccess().getUsersGame(); + usersArray = MathGame.getMySQLAccess().getUsersGame(); + if(usersArray == null) + return; updateUsersList(); // mathGame.sql.close(); } catch (Exception e) { @@ -372,106 +311,18 @@ public void refreshDatabase() { * Updates the list of users */ public void updateUsersList() { - // usersList.removeAll(); System.out.println("updating users " + usersArray.size()); - innerPanel.removeAll(); + usersList.setText(""); for (int i = 0; i < usersArray.size(); i++) { - System.out.println(usersArray.get(i)); - JLabel label = new JLabel(usersArray.get(i)); - label.setPreferredSize(new Dimension(100, 20)); - innerPanel.add(label); + //System.out.println(usersArray.get(i)); + usersList.append(usersArray.get(i)+'\n'); } usersList.revalidate(); usersList.repaint(); - } - - /** - * Starts the game - */ - public void startGame() { - // this.setVisible(false); - mathGame.showMenu(MathGame.Menu.GAME); - System.out.println("ENTER GAME"); - System.out.println("type1 " + typeManager.getType()); - typeManager.init(mathGame.getCardPanel()); - typeManager.randomize(); - } - - /** - * When you choose the fraction option - */ - public void chooseFraction() { - //this.setVisible(false); - - typeManager.setType(TypeManager.GameType.FRACTIONS); - System.out.println("Selected: fraction"); - } - - /** - * When you choose the decimal option - */ - public void chooseDecimal() { - // this.setVisible(false); - - typeManager.setType(TypeManager.GameType.DECIMALS); - System.out.println("Selected: decimal"); - } - - /** - * When you choose the integer option - */ - public void chooseInteger() { - // this.setVisible(false); - - typeManager.setType(TypeManager.GameType.INTEGERS); - System.out.println("Selected: integer"); - } - - /** - * When you choose the mixed option - */ - public void chooseMixed() { - //this.setVisible(false); - //TODO Implement a mixed mode; currently sets to Fraction mode - typeManager.setType(TypeManager.GameType.FRACTIONS); - System.out.println("Selected: mixed"); } - //TODO Implement the modeInfo functions - /** - * Displays info on the fraction mode - */ - public void fractionInfo() { - // info.setText("Choose this mode to work with fractions"); - // JOptionPane.showMessageDialog(this, "We need help in putting something that is worthwhile in this box."); - } - - /** - * Displays info on the decimal mode - */ - public void decimalInfo() { - //JOptionPane.showMessageDialog(this, "We need help in putting something that is worthwhile in this box."); - } - - /** - * Displays info on the integer mode - */ - public void integerinfo() { - // info.setText("Choose this mode to work with integers"); - // JOptionPane.showMessageDialog(this, "Game created by Academy Math Games Team. Menu created by Roland Fong and David Schildkraut."); - } - - /** - * Displays info on the mixed mode - */ - public void mixedinfo() { - // info.setText("Choose this mode to work with all of the types"); - // JOptionPane.showMessageDialog(this, "We need help in putting something that is worthwhile in this box."); - } - - @Override public void paintComponent(Graphics g){ super.paintComponents(g); @@ -487,17 +338,6 @@ public void mouseDragged(MouseEvent e) { public void mouseMoved(MouseEvent e) { mx = e.getX(); my = e.getY(); - - //TODO Delete this soon... - if(e.getSource() == home) { - fractionInfo(); - } else if(e.getSource() == host) { - decimalInfo(); - } else if(e.getSource() == join) { - integerinfo(); - } else if(e.getSource() == refresh) { - mixedinfo(); - } } @Override @@ -512,7 +352,7 @@ public void mouseEntered(MouseEvent e) { @Override public void mouseExited(MouseEvent e) { - System.out.println("Mouse Exited Button"); + } @Override @@ -534,14 +374,14 @@ private class GameCard extends JLabel { private static final long serialVersionUID = 2993530244820621535L; - int gameID; - int numPlayers; // 2 for now, but may introduce a solo mode or more than 2 players - String name; - String type; - String scoring; - String diff; - int rounds; //Number of rounds - ArrayList players; + private int gameID; + private int numPlayers; // 2 for now, but may introduce a solo mode or more than 2 players + private String name; + private String type; + private String scoring; + private String diff; + private int rounds; //Number of rounds + private ArrayList players; /** * @param ID - The ID of the game (the row number in database) @@ -578,23 +418,33 @@ public void mouseClicked(MouseEvent e) { if(!GameManager.getMatchesAccess().checkForFullGame()) { // If the game is not full - mathGame.getUser().setPlayerID(2);//TODO: Update this for any number of players - mathGame.showMenu(MathGame.Menu.GAME); + refreshTimer.stop(); + MathGame.getUser().setPlayerID(2);//TODO: Update this for any number of players + MathGame.setGameState(MathGame.GameState.COMPETITIVE); + MathGame.showMenu(MathGame.Menu.GAME); gameManager.joinGame(tempCard.getGameID()); System.out.println("GAME SET: " + tempCard.getGameID()); gameManager.setGame(GameManager.getMatchesAccess().getGame(tempCard.getGameID())); typeManager.setType(gameManager.getGame().getType()); - typeManager.randomize(); + try { + typeManager.randomize(); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } GameManager.getMatchesAccess().setMatchNum(tempCard.getGameID()); System.out.println("MATCHNUM " + GameManager.getMatchesAccess().getMatchNum()); - mathGame.getSidePanel().startTimer(tempCard.getType()); - mathGame.getSidePanel().setUpMultiplayer(); + MathGame.getSidePanel().startTimer(tempCard.getType()); + MathGame.getSidePanel().setUpMultiplayer(); } else { - JOptionPane.showMessageDialog(mathGame.getMenu(MathGame.Menu.MULTIMENU).getTopLevelAncestor(), "This game is full"); + //JOptionPane.showMessageDialog(MathGame.getMenu(MathGame.Menu.MULTIMENU).getTopLevelAncestor(), "This game is full"); + GameDialogFactory.showGameMessageDialog( + MathGame.getMenu(MathGame.Menu.MULTIMENU).getTopLevelAncestor(), + "Message", "This game is full", GameDialogFactory.OK); GameManager.getMatchesAccess().setMatchNum(-1); // The game is full, so do not join } } @@ -654,7 +504,6 @@ public String getType() { /** * @param type - The type to set (as a string) */ - @SuppressWarnings("unused") public void setType(String type) { this.type = type; } @@ -662,7 +511,6 @@ public void setType(String type) { /** * @return The number of players */ - @SuppressWarnings("unused") public int getNumberOfPlayers() { return numPlayers; } @@ -670,7 +518,6 @@ public int getNumberOfPlayers() { /** * @param numberOfPlayers - The number of players to set */ - @SuppressWarnings("unused") public void setNumberOfPlayers(int numberOfPlayers) { this.numPlayers = numberOfPlayers; } diff --git a/src/com/mathgame/menus/OptionMenu.java b/src/com/mathgame/menus/OptionMenu.java deleted file mode 100644 index f7c2b12..0000000 --- a/src/com/mathgame/menus/OptionMenu.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.mathgame.menus; - -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.ButtonGroup; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JToggleButton; - -import com.mathgame.math.MathGame; -import com.mathgame.math.SoundManager; -import com.mathgame.math.MathGame.GameState; -import com.mathgame.math.TypeManager; -import com.mathgame.math.TypeManager.Difficulty; -import com.mathgame.math.TypeManager.GameType; - -/** - * The OptionMenu class represents the menu for selecting game mode, number types, difficulty, and other game parameters - *

- * Multiple options for type can be selected (i.e. combine integers and decimals, etc.), but we - * will need either database sheet support or a class that can convert between forms (the latter is preferred) - * @author Roland - */ -public class OptionMenu extends JPanel implements ActionListener { - - //TODO Use tooltips when hovering over button - //TODO Undecided about scoring... Will sort it out later - //TODO Beautify layout some more (i.e. customize JRadioButtons, or perhaps extend Swing elements - - private static final long serialVersionUID = 2089592182201152773L; - - static final String BACKGROUND_FILE = "/images/background2.png"; - static final String BUTTON_IMAGE_FILE = "/images/MenuButtonImg1.png"; - static final String BUTTON_ROLLOVER_IMAGE_FILE = "/images/MenuButtonImg2.png"; - static final String BUTTON_PRESSED_IMAGE_FILE = "/images/MenuButtonImg3.png"; - static final int BUTTON_WIDTH = 130; - static final int BUTTON_HEIGHT = 30; - ImageIcon background; - ImageIcon buttonImage; - ImageIcon buttonRollOverImage; - ImageIcon buttonPressedImage; - - ButtonGroup modeGroup; // Practice or Competitive (aka single player or multiplayer) - ButtonGroup diffGroup; // Easy, Medium, Hard - ArrayList types; // Integer, Decimal, Fraction (To be added: Negative, Exponents, Log) - ArrayList modes; - ArrayList diffs; - - String[] modeNames = {"Practice", "Competitive"}; - String[] typeNames = {"Integer", "Decimal", "Fraction"}; - String[] diffNames = {"Easy", "Medium", "Hard"}; - - Map buttonMap; // Associate buttons with their names for easy locating - - JPanel modePanel; - JPanel typePanel; - JPanel diffPanel; - - JButton play; // Click to play the game! - - GridBagConstraints gbc; - - private static final Font eurostile24 = new Font("Eurostile", Font.PLAIN, 24); - // IDK why, but using the font from the MathGame class isn't working - - MathGame mathGame; - TypeManager tm; - - public OptionMenu(MathGame mathGame) { - this.mathGame = mathGame; - this.tm = mathGame.getTypeManager(); - - this.setLayout(new GridBagLayout()); - // this.setLayout(new FlowLayout(FlowLayout.CENTER)); - gbc = new GridBagConstraints(); - - // Set size - Dimension size = getPreferredSize(); - size.width = mathGame.getWidth(); - size.height = mathGame.getHeight(); - setPreferredSize(size); - - // Image initialization - background = new ImageIcon(OptionMenu.class.getResource(BACKGROUND_FILE)); - buttonImage = new ImageIcon(OptionMenu.class.getResource(BUTTON_IMAGE_FILE)); - buttonRollOverImage = new ImageIcon(OptionMenu.class.getResource(BUTTON_ROLLOVER_IMAGE_FILE)); - buttonPressedImage = new ImageIcon(OptionMenu.class.getResource(BUTTON_PRESSED_IMAGE_FILE)); - - // Button creation - buttonMap = new HashMap(); - initModes(); - initTypes(); - initDiffs(); - - // Default selections - modes.get(0).setSelected(true); - types.get(0).setSelected(true); - diffs.get(0).setSelected(true); - mathGame.setGameState(GameState.PRACTICE); - - play = new JButton("Play"); - play.setFont(eurostile24); - play.setHorizontalTextPosition(JButton.CENTER); - play.setVerticalTextPosition(JButton.CENTER); - play.setBorderPainted(false); - play.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT)); - play.addActionListener(this); - - try { - play.setIcon(buttonImage); - play.setRolloverIcon(buttonRollOverImage); - play.setPressedIcon(buttonPressedImage); - } catch (Exception ex) { - ex.printStackTrace(); - } - - gbc.insets = new Insets(5, 5, 5, 5); - gbc.gridwidth = 3; - gbc.gridheight = 3; - gbc.gridx = 0; - gbc.gridy = 0; - add(modePanel, gbc); - gbc.gridx = 4; - gbc.gridy = 0; - gbc.gridwidth = 3; - gbc.gridheight = 3; - add(typePanel, gbc); - gbc.gridx = 8; - gbc.gridy = 0; - gbc.weighty = 1; - gbc.gridwidth = 3; - gbc.gridheight = 3; - add(diffPanel, gbc); - gbc.gridx = 4; - gbc.gridy = 3; - add(play, gbc); - } - - /** - * Initialize the modes panel - */ - private void initModes() { - modes = new ArrayList(); - for(String s : modeNames) { - modes.add(new JRadioButton(s)); - } - modePanel = new JPanel(); - modePanel.setOpaque(false); - modePanel.setLayout(new GridBagLayout()); - modeGroup = new ButtonGroup(); - for (int i = 0; i < modes.size(); i++) { - modeGroup.add(modes.get(i)); - modes.get(i).setFont(eurostile24); - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.gridx = 0; - gbc.gridy = i; // Layout buttons going down same column - modePanel.add(modes.get(i), gbc); - buttonMap.put(modeNames[i], modes.get(i)); - modes.get(i).setOpaque(false); - modes.get(i).addActionListener(this); - } - } - - /** - * Initializes the types panel - */ - private void initTypes() { - types = new ArrayList(); - for (String s : typeNames) { - types.add(new JCheckBox(s)); - } - typePanel = new JPanel(); - typePanel.setLayout(new GridBagLayout()); - typePanel.setOpaque(false); - for (int i = 0; i < types.size(); i++) { - types.get(i).setFont(eurostile24); - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.gridx = 0; - gbc.gridy = i; // Layout buttons going down same column - typePanel.add(types.get(i), gbc); - buttonMap.put(typeNames[i], types.get(i)); - types.get(i).setOpaque(false); - // types.get(i).addActionListener(this); - } - } - - /** - * Initializes the difficulty panel - */ - private void initDiffs() { - diffs = new ArrayList(); - for (String s : diffNames) { - diffs.add(new JRadioButton(s)); - } - diffPanel = new JPanel(); - diffGroup = new ButtonGroup(); - diffPanel.setLayout(new GridBagLayout()); - diffPanel.setOpaque(false); - for (int i = 0; i < diffs.size(); i++) { - diffGroup.add(diffs.get(i)); - diffs.get(i).setFont(eurostile24); - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.gridx = 0; - gbc.gridy = i; // Layout buttons going down same column - diffPanel.add(diffs.get(i), gbc); - buttonMap.put(diffNames[i], diffs.get(i)); - diffs.get(i).setOpaque(false); - // diffs.get(i).addActionListener(this); - } - } - - /** - * Starts the game - */ - private void startGame() { - mathGame.showMenu(MathGame.Menu.GAME); - System.out.println("ENTER GAME"); - - mathGame.getSidePanel().startTimer("Mix"); //TODO Hardcoded to mixed scoring - - tm.init(mathGame.getCardPanel()); - } - - @Override - public void actionPerformed(ActionEvent e) { - if (e.getSource() instanceof JButton) { - SoundManager.playSound(SoundManager.SoundType.BUTTON); - } - - // Allow options only for practice mode (competitive decided through in game menu) - if (e.getSource() == buttonMap.get("Practice")) { - if (buttonMap.get("Practice").isSelected()) { - for (JRadioButton rb : diffs) { - rb.setEnabled(true); - } - for (JCheckBox cb : types) { - cb.setEnabled(true); - } - } - } else if(e.getSource() == buttonMap.get("Competitive")) { - if (buttonMap.get("Competitive").isSelected()) { - for (JRadioButton rb : diffs) { - rb.setEnabled(false); - } - for (JCheckBox cb : types) { - cb.setEnabled(false); - } - } - } else if (e.getSource() == play) { - if (buttonMap.get("Competitive").isSelected()) { - mathGame.setGameState(GameState.COMPETITIVE); - ((MultiMenu)(mathGame.getMenu(MathGame.Menu.MULTIMENU))).refreshDatabase(); - ((MultiMenu)(mathGame.getMenu(MathGame.Menu.MULTIMENU))).addThisUser(); - mathGame.showMenu(MathGame.Menu.MULTIMENU); - } else { - mathGame.setGameState(GameState.PRACTICE); - startGame(); - } - - if (buttonMap.get("Integer").isSelected()) { - tm.setType(GameType.INTEGERS); - } else if (buttonMap.get("Decimal").isSelected()) { - tm.setType(GameType.DECIMALS); - } else if (buttonMap.get("Fraction").isSelected()) { - tm.setType(GameType.FRACTIONS); - } else { - tm.setType(GameType.INTEGERS); - } - - // Etc. - - if (buttonMap.get("Easy").isSelected()) { - tm.setDiff(Difficulty.EASY); - tm.randomize(); - } else if (buttonMap.get("Medium").isSelected()) { - tm.setDiff(Difficulty.MEDIUM); - tm.randomize(); - } else if (buttonMap.get("Hard").isSelected()) { - tm.setDiff(Difficulty.HARD); - tm.randomize(); - } - } - } - - @Override - public void paintComponent(Graphics g){ - super.paintComponents(g); - g.drawImage(background.getImage(), 0, 0, OptionMenu.this); - } - -} diff --git a/src/com/mathgame/menus/RegisterMenu.java b/src/com/mathgame/menus/RegisterMenu.java new file mode 100644 index 0000000..6a435ed --- /dev/null +++ b/src/com/mathgame/menus/RegisterMenu.java @@ -0,0 +1,82 @@ +package com.mathgame.menus; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; + +import com.mathgame.guicomponents.GameButton; +import com.mathgame.math.MathGame; +import com.mathgame.math.SoundManager; + +/** + * The RegisterMenu class represents the menu used to register new players + */ +public class RegisterMenu extends JPanel implements ActionListener{ + + private JLabel usernameLabel; + private JLabel passwordLabel; + private JTextField usernameField; + private JTextField passwordField; + private GameButton registerButton; + private GameButton cancel; + + private static final String IMAGE_FILE = "/images/backMulti.png"; + + private static ImageIcon background = new ImageIcon(MultiMenu.class.getResource(IMAGE_FILE)); + + public RegisterMenu(){ + setLayout(null); + + usernameLabel = new JLabel("Username:"); + usernameLabel.setFont(MathGame.eurostile24); + usernameLabel.setBounds(320, 200, 110, 30); + + passwordLabel = new JLabel("Password:"); + passwordLabel.setFont(MathGame.eurostile24); + passwordLabel.setBounds(320, 240, 110, 30); + + usernameField = new JTextField(); + usernameField.setFont(MathGame.eurostile24); + usernameField.setBounds(440, 200, 150, 30); + + passwordField = new JPasswordField(); + passwordField.setFont(MathGame.eurostile24); + passwordField.setBounds(440, 240, 150, 30); + + registerButton = new GameButton("Register"); + registerButton.setLocation(400, 290); + registerButton.addActionListener(this); + + cancel = new GameButton("Cancel"); + cancel.setLocation(400,350); + cancel.addActionListener(this); + + this.add(usernameLabel); + this.add(passwordLabel); + this.add(usernameField); + this.add(passwordField); + this.add(registerButton); + this.add(cancel); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() instanceof GameButton) { + SoundManager.playSound(SoundManager.SoundType.BUTTON); + } + + if(e.getSource() == registerButton){ + MathGame.getMySQLAccess().registerUser(usernameField.getText(), passwordField.getText()); + MathGame.showMenu(MathGame.Menu.LOGIN); + } + else if(e.getSource() == cancel){ + MathGame.showMenu(MathGame.Menu.LOGIN); + } + + } +} diff --git a/src/com/mathgame/network/GameManager.java b/src/com/mathgame/network/GameManager.java index 74ff08a..6d6b8e8 100644 --- a/src/com/mathgame/network/GameManager.java +++ b/src/com/mathgame/network/GameManager.java @@ -6,27 +6,28 @@ import com.mathgame.math.MathGame; /** - * The GameManager class holds the details (specs) for multiplayer games + * The GameManager class holds the specifications for multiplayer games */ public class GameManager { private Game game; - @SuppressWarnings("unused") - private int score; // Current running total score of player //TODO Use this variable + @SuppressWarnings("unused") //TODO Use this variable + private int score; // Current running total score of player static MatchesAccess matchesAccess; - static MathGame mathGame; private ArrayList scores; // The scores of all players (in the order of what's in database (i.e. 1 is the host and not necessarily 'this' player) - @SuppressWarnings("unused") - private int currentRound; //TODO Use this variable + @SuppressWarnings("unused") //TODO Use this variable + private int currentRound; - public GameManager(MathGame mathGame) { - GameManager.mathGame = mathGame; - matchesAccess = new MatchesAccess(mathGame, mathGame.getMySQLAccess().getConnection()); + public GameManager() { + matchesAccess = new MatchesAccess(MathGame.getMySQLAccess().getConnection()); - scores = new ArrayList(2); // game.getNumberOfPlayers()); // Game is not initialized yet + scores = new ArrayList(2); + + // game.getNumberOfPlayers()); + // But, game is not initialized yet } /* @@ -36,8 +37,8 @@ public void reconnectStatement() { */ /** - * Adds the round score(s) to the cumulative score, along with the latest player score - * @param score - The (user) score to update + * Adds the round score to the cumulative score, along with the latest player score + * @param score - The round score to add */ public void updateScores(int score) { matchesAccess.updateScore(score); @@ -87,7 +88,7 @@ public void setCurrentRound(int currentRound) { } - /** + /** * @return The current Game */ public Game getGame() { @@ -101,19 +102,21 @@ public Game getGame() { public void setGame(Game game) { this.game = game; - // return matchesAccess.hostGame(); // Let the game begin! Er... well, when the other player gets here + // return matchesAccess.hostGame(); + // Let the game begin! Er... well, when the other player gets here } /** * Hosts a new game - * @return The match number (ID?) of the new game (from the database) + * @return The match number ID(?) of the new game (from the database) */ public int hostGame() { return matchesAccess.hostGame(); } /** - * Join a game (of the given gameID) that is being hosted + * Join the specified game that is being hosted + * @param gameID - The ID of the game to be joined */ public void joinGame(int gameID) { matchesAccess.joinGame(gameID); @@ -129,7 +132,7 @@ public ArrayList getCurrentGames() { /** * Checks whether the game is full (yet) - * @return Whether the game is filled (true) or not + * @return True if the game is filled */ public Boolean gameFilled() { return matchesAccess.checkForFullGame(); diff --git a/src/com/mathgame/network/User.java b/src/com/mathgame/network/User.java index fd624dc..6700748 100644 --- a/src/com/mathgame/network/User.java +++ b/src/com/mathgame/network/User.java @@ -1,5 +1,7 @@ package com.mathgame.network; +import com.mathgame.math.SoundManager; + /** * The User class represents the individual users */ @@ -33,12 +35,14 @@ public void uponGameEnd(Boolean won, int score, User rival) { if (won) { modifier = rival.getRankValue() / rankValue; gamesWon++; + SoundManager.playSound(SoundManager.SoundType.WIN); rankValue = rankValue + (score * modifier); } else { modifier = rankValue / rival.getRankValue(); modifier *= -1; gamesLost++; + SoundManager.playSound(SoundManager.SoundType.LOSE); rankValue = rankValue + ((1 / score) * modifier); } diff --git a/src/com/mathgame/offline/TypeManagerO.java b/src/com/mathgame/offline/TypeManagerO.java index 17252d6..d90afcf 100644 --- a/src/com/mathgame/offline/TypeManagerO.java +++ b/src/com/mathgame/offline/TypeManagerO.java @@ -15,6 +15,7 @@ import com.mathgame.cards.NumberCard; import com.mathgame.math.Calculate; +import com.mathgame.math.TypeManager.GameType; import com.mathgame.panels.CardPanel; import java.math.BigDecimal; @@ -24,17 +25,10 @@ /** * The TypeManagerO class handles the different types of games and converts between values of different types. * It is designed for offline play (unlike the TypeManager class), and it does not contain it's own MathGame object + * @deprecated */ public class TypeManagerO { - NumberCard card1; - NumberCard card2; - NumberCard card3; - NumberCard card4; - NumberCard card5; - NumberCard card6; - NumberCard ans; - CardPanel cP; Calculate calc; @@ -146,14 +140,6 @@ public Difficulty getDiff(){ public void init(CardPanel cP) { this.cP = cP; - this.card1 = cP.card1; - this.card2 = cP.card2; - this.card3 = cP.card3; - this.card4 = cP.card4; - this.card5 = cP.card5; - this.card6 = cP.card6; - this.ans = cP.ans; - this.values = cP.values; } @@ -373,100 +359,48 @@ public ArrayList randomIntegerValues() { * Assigns random values to the number cards */ public void randomize() { - if(gameType == GameType.FRACTIONS) { + if (gameType == GameType.FRACTIONS) { ArrayList newValues = randomFractionValues(); - card1.setStrValue(convertDecimaltoFraction(newValues.get(0))); - card2.setStrValue(convertDecimaltoFraction(newValues.get(1))); - card3.setStrValue(convertDecimaltoFraction(newValues.get(2))); - card4.setStrValue(convertDecimaltoFraction(newValues.get(3))); - card5.setStrValue(convertDecimaltoFraction(newValues.get(4))); - card6.setStrValue(convertDecimaltoFraction(newValues.get(5))); - - values.set(0, card1.getStrValue()); - values.set(1, card2.getStrValue()); - values.set(2, card3.getStrValue()); - values.set(3, card4.getStrValue()); - values.set(4, card5.getStrValue()); - values.set(5, card6.getStrValue()); - ans.setStrValue(currentRow.getCell(4).getStringCellValue()); - System.out.println(newValues.get(0)); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cP.getCards()[i].setStrValue(convertDecimaltoFraction(newValues.get(i))); + values.set(i, cP.getCards()[i].getStrValue()); + cP.getCards()[i].setValue(newValues.get(i)); + } - card1.setValue(String.valueOf(newValues.get(0))); - card2.setValue(String.valueOf(newValues.get(1))); - card3.setValue(String.valueOf(newValues.get(2))); - card4.setValue(String.valueOf(newValues.get(3))); - card5.setValue(String.valueOf(newValues.get(4))); - card6.setValue(String.valueOf(newValues.get(5))); - ans.setValue(String.valueOf(NumberCard.parseNumFromText(ans.getStrValue()))); - // card1.parseNumFromText(newValues.get(3)) + cP.getAns().setStrValue(currentRow.getCell(4).getStringCellValue()); + cP.getAns().setValue(NumberCard.parseNumFromText(cP.getAns().getStrValue())); } else if(gameType == GameType.DECIMALS) { ArrayList newValues = randomDecimalValues(); - card1.setStrValue(String.valueOf(newValues.get(0))); - card2.setStrValue(String.valueOf(newValues.get(1))); - card3.setStrValue(String.valueOf(newValues.get(2))); - card4.setStrValue(String.valueOf(newValues.get(3))); - card5.setStrValue(String.valueOf(newValues.get(4))); - card6.setStrValue(String.valueOf(newValues.get(5))); - - values.set(0, card1.getStrValue()); - values.set(1, card2.getStrValue()); - values.set(2, card3.getStrValue()); - values.set(3, card4.getStrValue()); - values.set(4, card5.getStrValue()); - values.set(5, card6.getStrValue()); - ans.setStrValue(String.valueOf(currentRow.getCell(4).getNumericCellValue())); - System.out.println(newValues.get(0)); - - - card1.setValue(String.valueOf(newValues.get(0))); - card2.setValue(String.valueOf(newValues.get(1))); - card3.setValue(String.valueOf(newValues.get(2))); - card4.setValue(String.valueOf(newValues.get(3))); - card5.setValue(String.valueOf(newValues.get(4))); - card6.setValue(String.valueOf(newValues.get(5))); - ans.setValue(String.valueOf(NumberCard.parseNumFromText(ans.getStrValue()))); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cP.getCards()[i].setStrValue(String.valueOf(newValues.get(i))); + values.set(i, cP.getCards()[i].getStrValue()); + cP.getCards()[i].setValue(newValues.get(i)); + } + + cP.getAns().setStrValue(String.valueOf(currentRow.getCell(4).getNumericCellValue())); + cP.getAns().setValue(NumberCard.parseNumFromText(cP.getAns().getStrValue())); } else{ ArrayList newValues = randomIntegerValues(); - card1.setStrValue(String.valueOf(newValues.get(0))); - card2.setStrValue(String.valueOf(newValues.get(1))); - card3.setStrValue(String.valueOf(newValues.get(2))); - card4.setStrValue(String.valueOf(newValues.get(3))); - card5.setStrValue(String.valueOf(newValues.get(4))); - card6.setStrValue(String.valueOf(newValues.get(5))); - - values.set(0, card1.getStrValue()); - values.set(1, card2.getStrValue()); - values.set(2, card3.getStrValue()); - values.set(3, card4.getStrValue()); - values.set(4, card5.getStrValue()); - values.set(5, card6.getStrValue()); - ans.setStrValue(String.valueOf(currentRow.getCell(4).getNumericCellValue())); - System.out.println(newValues.get(0)); - - - card1.setValue(String.valueOf(newValues.get(0))); - card2.setValue(String.valueOf(newValues.get(1))); - card3.setValue(String.valueOf(newValues.get(2))); - card4.setValue(String.valueOf(newValues.get(3))); - card5.setValue(String.valueOf(newValues.get(4))); - card6.setValue(String.valueOf(newValues.get(5))); - ans.setValue(String.valueOf(NumberCard.parseNumFromText(ans.getStrValue()))); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cP.getCards()[i].setStrValue(String.valueOf(newValues.get(i))); + values.set(i, cP.getCards()[i].getStrValue()); + cP.getCards()[i].setValue(newValues.get(i)); + } + cP.getAns().setStrValue(String.valueOf(currentRow.getCell(4).getNumericCellValue())); + cP.getAns().setValue(NumberCard.parseNumFromText(cP.getAns().getStrValue())); } // Tag each card with "home" (cardPanel) being original location - card1.setHome("home"); - card2.setHome("home"); - card3.setHome("home"); - card4.setHome("home"); - card5.setHome("home"); - card6.setHome("home"); - ans.setHome("home"); + for(int i = 0; i < CardPanel.NUM_OF_CARDS; i++) { + cP.getCards()[i].setHome("home"); + } + cP.getAns().setHome("home"); } } diff --git a/src/com/mathgame/panels/CardPanel.java b/src/com/mathgame/panels/CardPanel.java index 3a33911..4c975c4 100644 --- a/src/com/mathgame/panels/CardPanel.java +++ b/src/com/mathgame/panels/CardPanel.java @@ -12,9 +12,6 @@ import com.mathgame.math.MathGame; import com.mathgame.math.TypeManager; -import org.apache.poi.xssf.usermodel.*; - -import java.io.InputStream; /** @@ -22,219 +19,83 @@ */ public class CardPanel extends JPanel{ + private static final long serialVersionUID = -3726881692277688183L; - - MathGame mathGame; - public NumberCard card1; - public NumberCard card2; - public NumberCard card3; - public NumberCard card4; - public NumberCard card5; - public NumberCard card6; - public NumberCard ans; - static final String IMAGE_FILE = "/images/CardBar.png"; + public static final int NUM_OF_CARDS = 6;//there are 6 cards + private NumberCard cards[]; + private NumberCard ans; + private static final String IMAGE_FILE = "/images/CardBar.png"; - ImageIcon background; + private ImageIcon background; - ValidationBox v1; - ValidationBox v2; - ValidationBox v3; - ValidationBox v4; - ValidationBox v5; - ValidationBox v6; - ValidationBox v_ans; + private ValidationBox vboxes[]; + private ValidationBox v_ans; - JLayeredPane masterLayer; + private JLayeredPane masterLayer; - Calculate calc; + private Calculate calc; public ArrayList values; - ArrayList cardExists; + private ArrayList cardExists; - InputStream cardValueInput; - XSSFWorkbook cardValueWorkbook; - static final String CARD_VALUE_FILE = "values.xlsx"; - XSSFSheet currentSheet; - int rowCount; - int currentRowNumber; - XSSFRow currentRow; + //TODO use for offline play? + /*private InputStream cardValueInput; + private XSSFWorkbook cardValueWorkbook; + private static final String CARD_VALUE_FILE = "values.xlsx"; + private XSSFSheet currentSheet; + private int rowCount; + private int currentRowNumber; + private XSSFRow currentRow;*/ - TypeManager typeManager; + private TypeManager typeManager; - public CardPanel(MathGame mathGame){ - this.mathGame = mathGame; - this.typeManager = mathGame.getTypeManager(); + public CardPanel() { + this.typeManager = MathGame.getTypeManager(); } /** * Initializes a card panel * @param masterLayer - The JLayeredPane that contains the CardPanel */ - public void init (JLayeredPane masterLayer) { + public void init () { this.setBounds(0, 0, 750, 150); setLayout(null); - this.masterLayer = masterLayer; + this.masterLayer = MathGame.getMasterPane(); cardExists = new ArrayList(); for (int i = 0; i < 6; i++) { cardExists.add(true); } - // TitledBorder cardBorder = BorderFactory.createTitledBorder("My Cards"); - // this.setBorder(cardBorder);//currently for visibility; may need to be removed later - // NumberCard testn = new NumberCard("2/3"); - - card1 = new NumberCard(1); - card2 = new NumberCard(2); - card3 = new NumberCard(3); - card4 = new NumberCard(4); - card5 = new NumberCard(5); - card6 = new NumberCard(6); - ans = new NumberCard(0); + background = new ImageIcon(CardPanel.class.getResource(IMAGE_FILE)); - v1 = new ValidationBox(card1); - v2 = new ValidationBox(card2); - v3 = new ValidationBox(card3); - v4 = new ValidationBox(card4); - v5 = new ValidationBox(card5); - v6 = new ValidationBox(card6); - v_ans = new ValidationBox(ans); + values = new ArrayList(); - card1.setNumberTag(0); - card2.setNumberTag(1); - card3.setNumberTag(2); - card4.setNumberTag(3); - card5.setNumberTag(4); - card6.setNumberTag(5); + cards = new NumberCard[6]; + vboxes = new ValidationBox[6]; - card1.setBounds(20, 15, 80, 100); - card2.setBounds(110, 15, 80, 100); - card3.setBounds(200, 15, 80, 100); - card4.setBounds(290, 15, 80, 100); - card5.setBounds(380, 15, 80, 100); - card6.setBounds(470, 15, 80, 100); + ans = new NumberCard(0); ans.setBounds(650, 15, 80, 100); - - v1.setBounds(20, 115, 80, 20); - v2.setBounds(110, 115, 80, 20); - v3.setBounds(200, 115, 80, 20); - v4.setBounds(290, 115, 80, 20); - v5.setBounds(380, 115, 80, 20); - v6.setBounds(470, 115, 80, 20); - v_ans.setBounds(650, 115, 80, 20); - - this.add(card1); - this.add(card2); - this.add(card3); - this.add(card4); - this.add(card5); - this.add(card6); this.add(ans); - - this.add(v1); - this.add(v2); - this.add(v3); - this.add(v4); - this.add(v5); - this.add(v6); + v_ans = new ValidationBox(ans); + v_ans.setBounds(650, 115, 80, 20); this.add(v_ans); - // background = mathGame.getImage(mathGame.getDocumentBase(), imageFile); - background = new ImageIcon(CardPanel.class.getResource(IMAGE_FILE)); - - values = new ArrayList(); - - values.add(card1.getStrValue()); - values.add(card2.getStrValue()); - values.add(card3.getStrValue()); - values.add(card4.getStrValue()); - values.add(card5.getStrValue()); - values.add(card6.getStrValue()); + for(int i = 0; i < NUM_OF_CARDS; i++) { + cards[i] = new NumberCard(i); + cards[i].setNumberTag(i); + cards[i].setBounds(20 + 90 * i, 15, 80, 100); + values.add(cards[i].getStrValue()); + vboxes[i] = new ValidationBox(cards[i]); + vboxes[i].setBounds(20 + 90 * i, 115, 80, 20); + this.add(cards[i]); + this.add(vboxes[i]); + } calc = new Calculate(); typeManager.init(this); } - /** - * @return An ArrayList of randomly-generated values (to be replaced in future versions when the database is completed) - */ - /* - public ArrayList randomValues() { - Random generator = new Random(); - currentRowNumber = (int)(generator.nextFloat() * rowCount); - System.out.println("Current row: " + (currentRowNumber + 1)); - currentRow = currentSheet.getRow(currentRowNumber); - ArrayList cardValues = new ArrayList(); - for (int x = 0; x < 6; x++) { - cardValues.add(""+generator.nextInt(21)); - } - int RandomInsert1 = (int)(generator.nextFloat() * 6); - int RandomInsert2; - do { - RandomInsert2 = (int)(generator.nextFloat() * 6); - } while (RandomInsert2 == RandomInsert1); - - // cardValues.set(RandomInsert1, (int)currentRow.getCell(1).getNumericCellValue()); - // cardValues.set(RandomInsert2, (int)currentRow.getCell(3).getNumericCellValue()); - - cardValues.set(RandomInsert1, currentRow.getCell(1).getStringCellValue()); - cardValues.set(RandomInsert2, currentRow.getCell(3).getStringCellValue()); - - return cardValues; - } - */ - - /** - * Takes in an ArrayList of values and assigns them to the cards - * @param newValues - The ArrayList of values (as strings) - */ - /* - public void randomize(ArrayList newValues){ - card1.setText(newValues.get(0)); - card2.setText(newValues.get(1)); - card3.setText(newValues.get(2)); - card4.setText(newValues.get(3)); - card5.setText(newValues.get(4)); - card6.setText(""+newValues.get(5)); - - values.set(0, card1.getText()); - values.set(1, card2.getText()); - values.set(2, card3.getText()); - values.set(3, card4.getText()); - values.set(4, card5.getText()); - values.set(5, card6.getText()); - ans.setText(currentRow.getCell(4).getStringCellValue()); - System.out.println(newValues.get(0)); - - card1.setValue(newValues.get(0)); - card2.setValue(newValues.get(1)); - card3.setValue(newValues.get(2)); - card4.setValue(newValues.get(3)); - card5.setValue(newValues.get(4)); - card6.setValue(newValues.get(5)); - ans.setValue(""+card1.parseNumFromText(ans.getText())); - - - v1.setCardValue(card1.getValue()); - v2.setCardValue(card2.getValue()); - v3.setCardValue(card3.getValue()); - v4.setCardValue(card4.getValue()); - v5.setCardValue(card5.getValue()); - v6.setCardValue(card6.getValue()); - v_ans.setCardValue(ans.getValue()); - - // card1.parseNumFromText(newValues.get(3)) - // Tag each card with "home" (cardpanel) as the original location - card1.setHome("home"); - card2.setHome("home"); - card3.setHome("home"); - card4.setHome("home"); - card5.setHome("home"); - card6.setHome("home"); - ans.setHome("home"); - } - */ - /** * Change whether the card with the given index exists * @param index - The card's index @@ -257,41 +118,16 @@ public Boolean getCardExistence(int index) { * @param cardValue - The card's value (as a string) */ public void restoreCard(String cardValue) { - for (int i = 0; i < 6; i++) { - System.out.println("values from reset " + values.get(i)); - } System.out.println("cardValue passed " + cardValue); - - if (cardValue.equals(values.get(0)) && !cardExists.get(0)) { - System.out.println("reset 0"); - card1.setBounds(20, 15, 80, 120); - masterLayer.add(card1, new Integer(1)); - cardExists.set(0, true); - } else if (cardValue.equals(values.get(1)) && !cardExists.get(1)) { - System.out.println("reset 1"); - card2.setBounds(110, 15, 80, 120); - masterLayer.add(card2, new Integer(1)); - cardExists.set(1, true); - } else if (cardValue.equals(values.get(2)) && !cardExists.get(2)) { - System.out.println("reset 2"); - card3.setBounds(200, 15, 80, 120); - masterLayer.add(card3, new Integer(1)); - cardExists.set(2, true); - } else if (cardValue.equals(values.get(3)) && !cardExists.get(3)) { - System.out.println("reset 3"); - card4.setBounds(290, 15, 80, 120); - masterLayer.add(card4, new Integer(1)); - cardExists.set(3, true); - } else if(cardValue.equals(values.get(4)) && !cardExists.get(4)) { - System.out.println("reset 4"); - card5.setBounds(380, 15, 80, 120); - masterLayer.add(card5, new Integer(1)); - cardExists.set(4, true); - } else if(cardValue.equals(values.get(5)) && !cardExists.get(5)) { - System.out.println("reset 5"); - card6.setBounds(470, 15, 80, 120); - masterLayer.add(card6, new Integer(1)); - cardExists.set(5, true); + for (int i = 0; i < NUM_OF_CARDS; i++) { + System.out.println("values from reset " + values.get(i)); + if(cardValue.equals(values.get(i)) && !cardExists.get(i)) { + System.out.println("reset "+i); + cards[i].setBounds(20 + 90 * i, 15, 80, 120); + masterLayer.add(cards[i], new Integer(1)); + cardExists.set(i, true); + break; + } } } @@ -299,53 +135,47 @@ public void restoreCard(String cardValue) { * Resets all validation boxes */ public void resetValidationBoxes(){ - v1.reset(); - v2.reset(); - v3.reset(); - v4.reset(); - v5.reset(); - v6.reset(); v_ans.reset(); + for(int i = 0; i < NUM_OF_CARDS; i++) + vboxes[i].reset(); } /** * Sets the visibility of cards to false, meaning all cards are hidden */ public void hideCards() { - card1.setVisible(false); - card2.setVisible(false); - card3.setVisible(false); - card4.setVisible(false); - card5.setVisible(false); - card6.setVisible(false); ans.setVisible(false); - v1.setVisible(false); - v2.setVisible(false); - v3.setVisible(false); - v4.setVisible(false); - v5.setVisible(false); - v6.setVisible(false); v_ans.setVisible(false); + for(int i = 0; i < NUM_OF_CARDS; i++) { + cards[i].setVisible(false); + vboxes[i].setVisible(false); + } } /** * Sets visibility of cards to true, meaning all cards are visible */ public void showCards() { - card1.setVisible(true); - card2.setVisible(true); - card3.setVisible(true); - card4.setVisible(true); - card5.setVisible(true); - card6.setVisible(true); ans.setVisible(true); - v1.setVisible(true); - v2.setVisible(true); - v3.setVisible(true); - v4.setVisible(true); - v5.setVisible(true); - v6.setVisible(true); v_ans.setVisible(true); + for(int i = 0; i < NUM_OF_CARDS; i++) { + cards[i].setVisible(true); + vboxes[i].setVisible(true); + } + } + + /** + * @return the cards + */ + public NumberCard[] getCards() { + return cards; + } + + /** + * @return the ans + */ + public NumberCard getAns() { + return ans; } @Override diff --git a/src/com/mathgame/panels/HoldPanel.java b/src/com/mathgame/panels/HoldPanel.java index 050ac52..6edc97b 100644 --- a/src/com/mathgame/panels/HoldPanel.java +++ b/src/com/mathgame/panels/HoldPanel.java @@ -22,9 +22,9 @@ public class HoldPanel extends JPanel { private static final long serialVersionUID = -2013522168342802483L; static final String IMAGE_FILE = "/images/card holder.png"; - ImageIcon background; + private ImageIcon background; - public void init(MathGame mathGame) { + public void init() { this.setLayout(new FlowLayout()); Border empty = BorderFactory.createEmptyBorder(10,10,10,10); this.setBorder(empty); @@ -35,7 +35,6 @@ public void init(MathGame mathGame) { size.height = 150; setPreferredSize(size); - // background = mathGame.getImage(mathGame.getDocumentBase(), imageFile); background = new ImageIcon(HoldPanel.class.getResource(IMAGE_FILE)); } diff --git a/src/com/mathgame/panels/OperationPanel.java b/src/com/mathgame/panels/OperationPanel.java index 6256191..741d59f 100644 --- a/src/com/mathgame/panels/OperationPanel.java +++ b/src/com/mathgame/panels/OperationPanel.java @@ -22,33 +22,34 @@ public class OperationPanel extends JPanel public OperationCard subtract; public OperationCard multiply; public OperationCard divide; + public OperationCard exponent; + //TODO EXPONENT: Add the exponent card (DONE) static final String IMAGE_FILE = "/images/Operation bar.png"; - ImageIcon background; + private ImageIcon background; - JLayeredPane masterLayer; + private JLayeredPane masterLayer; /** * Initialize the OperationPanel, using the MathGame as a JLayeredPane - * - * @param mathGame - The MathGame that contains the master layer - * @param mover - The CompMover object that will handle the moving of cards */ - public void init(MathGame mathGame, CompMover mover) + public void init() { setLayout(null); // TitledBorder opBorder = BorderFactory.createTitledBorder("Operation Panel"); // this.setBorder(new LineBorder(Color.black)); - add = new OperationCard(mathGame, "add"); - subtract = new OperationCard(mathGame, "subtract"); - multiply = new OperationCard(mathGame, "multiply"); - divide = new OperationCard(mathGame, "divide"); + add = new OperationCard("add"); + subtract = new OperationCard("subtract"); + multiply = new OperationCard("multiply"); + divide = new OperationCard("divide"); + exponent = new OperationCard("exponent"); add.setBounds(20, 160, 40, 40); subtract.setBounds(80, 160, 40, 40); multiply.setBounds(140, 160, 40, 40); divide.setBounds(200, 160, 40, 40); + exponent.setBounds(260, 160, 40, 40); Dimension panelsize = new Dimension(750,60); this.setPreferredSize(panelsize); @@ -56,8 +57,10 @@ public void init(MathGame mathGame, CompMover mover) this.add(subtract); this.add(multiply); this.add(divide); + this.add(exponent); + //TODO EXPONENT: Add and initialize the exponent card. Use the "operation bar.png" as reference (DONE) - masterLayer = mathGame.getMasterPane(); + masterLayer = MathGame.getMasterPane(); // background = mathGame.getImage(mathGame.getDocumentBase(), imageFile); background = new ImageIcon(OperationPanel.class.getResource(IMAGE_FILE)); @@ -81,7 +84,11 @@ public void addOperator(String op) { } else if (op.equals("divide")) { divide.setBounds(200, 160, 40, 40); masterLayer.add(divide, new Integer(1)); + } else if (op.equals("exponent")) { + exponent.setBounds(260, 160, 40, 40); + masterLayer.add(exponent, new Integer(1)); } + //TODO EXPONENT: Add the exponent card (DONE) } @Override diff --git a/src/com/mathgame/panels/SidePanel.java b/src/com/mathgame/panels/SidePanel.java index 26599aa..3807aeb 100644 --- a/src/com/mathgame/panels/SidePanel.java +++ b/src/com/mathgame/panels/SidePanel.java @@ -6,6 +6,8 @@ import com.mathgame.cards.OperationCard; import com.mathgame.cardmanager.UndoButton; import com.mathgame.database.MatchesAccess; +import com.mathgame.guicomponents.GameButton; +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.MathGame; import com.mathgame.math.SoundManager; import com.mathgame.math.TypeManager; @@ -24,635 +26,596 @@ */ public class SidePanel extends JPanel implements ActionListener { - private static final long serialVersionUID = -1209424284690306920L; - - MathGame mathGame; - - TypeManager typeManager; - ScoringSystem scorekeeper; - - JLabel clock; - JLabel pass; // Counts how many you get right - JLabel fail; // Counts how many you get wrong - JLabel score; - JLabel vs; - - JButton help; - JButton exit; - JButton checkAns; - UndoButton undo; - JButton reset; - - private static final Font eurostile36 = new Font("Eurostile", Font.PLAIN, 36); - private static final Font eurostile16 = new Font("Eurostile", Font.PLAIN, 16); - - static final String IMAGE_FILE = "/images/control bar.png"; - static final String BUTTON_IMAGE_FILE = "/images/DefaultButtonImage1.png"; - static final String BUTTON_ROLLOVER_IMAGE_FILE = "/images/DefaultButtonImage2.png"; - static final String BUTTON_PRESSED_IMAGE_FILE = "/images/DefaultButtonImage3.png"; - - ImageIcon buttonImage; - ImageIcon buttonRollOverImage; - ImageIcon buttonPressedImage; - - ImageIcon background; - - MatchesAccess matchesAccess; - GameManager gameManager; - - int score1 = 0; - int score2 = 0; - - // JTextArea error; - - JButton toggle; - - int correct = 0; - int wrong = 0; - int points = 0; - - public Timer timer; // This is public so that it can be accessed by SubMenu.java (to be started at the right time) - // StopWatch stopWatch; - - private boolean pressed = true; - - public long startTime = 0; - long endTime = 0; - - Insets insets = getInsets(); // Insets for the side panel for layout purposes - - public void init(MathGame mathGame) { - this.mathGame = mathGame; - - typeManager = mathGame.getTypeManager(); - scorekeeper = new ScoringSystem(); - gameManager = mathGame.getGameManager(); - matchesAccess = GameManager.getMatchesAccess(); - - // this.setBorder(new LineBorder(Color.BLACK)); - this.setBounds(750, 0, 150, 620); - - this.setLayout(null); - - // Instantiate controls - clock = new JLabel("00:00"); - toggle = new JButton("Start/Stop"); - score = new JLabel("0"); - help = new JButton("Help"); - exit = new JButton("Back"); - checkAns = new JButton("Check Answer"); - undo = new UndoButton("Undo Move", mathGame); - reset = new JButton("Reset"); - vs = new JLabel(); - - pass = new JLabel("Correct: " + correct); - fail = new JLabel("Wrong: " + wrong); - - background = new ImageIcon(SidePanel.class.getResource(IMAGE_FILE)); - buttonImage = new ImageIcon(MainMenu.class.getResource(BUTTON_IMAGE_FILE)); - buttonRollOverImage = new ImageIcon(MainMenu.class.getResource(BUTTON_ROLLOVER_IMAGE_FILE)); - buttonPressedImage = new ImageIcon(MainMenu.class.getResource(BUTTON_PRESSED_IMAGE_FILE)); - - add(clock); - add(toggle); - add(score); - add(help); - add(exit); - add(checkAns); - add(undo); - add(reset); - add(vs); - - // Define properties of controls - clock.setBounds(10, 10, 130, 60); - clock.setFont(eurostile36); - clock.setHorizontalAlignment(SwingConstants.CENTER); - - score.setBounds(10, 80, 130, 60); - score.setFont(eurostile36); - score.setHorizontalAlignment(SwingConstants.CENTER); - - toggle.setBounds(10, 150, 130, 30); - toggle.addActionListener(this); - toggle.setHorizontalTextPosition(JButton.CENTER); - toggle.setVerticalTextPosition(JButton.CENTER); - toggle.setFont(eurostile16); - toggle.setBorderPainted(false); - - undo.setBounds(10, 190, 130, 30); - undo.addActionListener(this); - undo.setHorizontalTextPosition(JButton.CENTER); - undo.setVerticalTextPosition(JButton.CENTER); - undo.setFont(eurostile16); - undo.setBorderPainted(false); - - reset.setBounds(10, 230, 130, 30); - reset.addActionListener(this); - reset.setHorizontalTextPosition(JButton.CENTER); - reset.setVerticalTextPosition(JButton.CENTER); - reset.setFont(eurostile16); - reset.setBorderPainted(false); - - checkAns.setBounds(10, 270, 130, 30); - checkAns.addActionListener(this); - checkAns.setHorizontalTextPosition(JButton.CENTER); - checkAns.setVerticalTextPosition(JButton.CENTER); - checkAns.setFont(eurostile16); - checkAns.setBorderPainted(false); - - vs.setBounds(10, 310, 130, 30); - vs.setFont(eurostile16); - vs.setHorizontalAlignment(SwingConstants.CENTER); - vs.setText("Vs. " + "nobody"); //TODO When versing someone, replace "nobody" with opponent name - - help.setBounds(10, 540, 130, 30); - help.setHorizontalAlignment(SwingConstants.CENTER); - help.addActionListener(this); - help.setHorizontalTextPosition(JButton.CENTER); - help.setVerticalTextPosition(JButton.CENTER); - help.setFont(eurostile16); - help.setBorderPainted(false); - - exit.setBounds(10, 580, 130, 30); - exit.setHorizontalAlignment(SwingConstants.CENTER); - exit.addActionListener(this); - exit.setHorizontalTextPosition(JButton.CENTER); - exit.setVerticalTextPosition(JButton.CENTER); - exit.setFont(eurostile16); - exit.setBorderPainted(false); - - timer = new Timer(1000, this); - timer.setRepeats(true); - - try { - toggle.setIcon(buttonImage); - toggle.setRolloverIcon(buttonRollOverImage); - toggle.setPressedIcon(buttonPressedImage); - help.setIcon(buttonImage); - help.setRolloverIcon(buttonRollOverImage); - help.setPressedIcon(buttonPressedImage); - undo.setIcon(buttonImage); - undo.setRolloverIcon(buttonRollOverImage); - undo.setPressedIcon(buttonPressedImage); - reset.setIcon(buttonImage); - reset.setRolloverIcon(buttonRollOverImage); - reset.setPressedIcon(buttonPressedImage); - checkAns.setIcon(buttonImage); - checkAns.setRolloverIcon(buttonRollOverImage); - checkAns.setPressedIcon(buttonPressedImage); - exit.setIcon(buttonImage); - exit.setRolloverIcon(buttonRollOverImage); - exit.setPressedIcon(buttonPressedImage); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public void startTimer(String type){ - timer.start(); - startTime = System.currentTimeMillis(); - scorekeeper.setGameType(type); - scorekeeper.setTimeStart(startTime); - - } - @Override - public void paintComponent(Graphics g) { - super.paintComponents(g); - g.drawImage(background.getImage(), 0, 0, SidePanel.this); - } - - @Override - public void actionPerformed(ActionEvent e) { - if (e.getSource() instanceof JButton && e.getSource() != checkAns) { // checkAns has its own sound effects - SoundManager.playSound(SoundManager.SoundType.BUTTON); - } - - if (e.getSource() == toggle) { - - if (!pressed) { - timer.start(); - startTime = System.currentTimeMillis(); - scorekeeper.setTimeStart(startTime); - pressed = true; - } else { - timer.stop(); - pressed = false; - } - } else if (e.getSource() == help) { - //TODO Decide function of Help (on website or in-game or just a hint) - JOptionPane.showMessageDialog(this, "Instructions go here"); - } else if (e.getSource() == checkAns) { - if (mathGame.getWorkspacePanel().getComponentCount() == 1) { - NumberCard finalAnsCard; - Component finalAnsComp = mathGame.getWorkspacePanel().getComponent(0); - String computedAns; // The answer the user got - String actualAns; // The actual answer - if (finalAnsComp instanceof NumberCard) { - finalAnsCard = (NumberCard)finalAnsComp; - actualAns = mathGame.getCardPanel().ans.getValue(); - computedAns = finalAnsCard.getValue(); - System.out.println(actualAns + " ?= " + computedAns); - if (actualAns.equals(computedAns) || - NumberCard.parseNumFromText(actualAns) == NumberCard.parseNumFromText(computedAns)) { - // If the player's answer is right... - - if (mathGame.getGameState() == GameState.COMPETITIVE) { - // This player is done! Tell the database - points = (int)(scorekeeper.uponWinning(System.currentTimeMillis(), undo.getIndex() + 1)); - gameManager.updateScores(points); - - // Wait for others to finish and get score - timer.stop(); - pressed = false; - - Thread waitForPlayer = new Thread() { - public void run() { - mathGame.getCardPanel().hideCards(); // Hide cards for the next round - - System.out.println("WAIT FOR OTHER PLAYER START"); - while(!GameManager.getMatchesAccess().checkForPlayersScoresUpdated(score1, score2)) { - // Wait for other player to finish; get from database - System.out.println("waiting for other player"); - } - System.out.println("WAIT FOR OTHER PLAYER END"); - - exit.setEnabled(true); - // Temporarily enable back button in case user wants to exit - - // Display scores in round summary (for a 10 seconds) - // Figure out when it's the last round to show the total match summary (if not finished yet...) - - // Meaningless statements? - gameManager.getCurrentRound(); - gameManager.getGame().getRounds(); - - System.out.println("ROUND " + gameManager.getCurrentRound() + "/" + gameManager.getGame().getRounds()); - - if(gameManager.getCurrentRound() != gameManager.getGame().getRounds()) { - String playerPointsString = "ROUND " + gameManager.getCurrentRound() + "\n"; - // Assume 2 players for now - for (int i = 1; i <= 2; i++) { - playerPointsString += gameManager.getGame().getPlayer(i) + ": " + gameManager.getRoundScores().get(i - 1) + "\n"; - } - score1 = gameManager.getRoundScores().get(0); - score2 = gameManager.getRoundScores().get(1); - System.out.println("score1 " + score1); - System.out.println("score2 " + score2); - - //Database should only be updated with the new round number once - if (mathGame.getUser().getPlayerID() == 1) { - GameManager.getMatchesAccess().incrementRound(); - } - - // JOptionPane.showMessageDialog(this, playerPointsString, "Round Summary", JOptionPane.PLAIN_MESSAGE); - - System.out.println ("SUMMARY DIALOG; player points: " + playerPointsString); - SummaryDialog sd = new SummaryDialog((JFrame)(mathGame.getSidePanel().getTopLevelAncestor()), "Round Summary", playerPointsString); - sd.pack(); - sd.setVisible(true); - } else { - // If this is the last match - - String playerPointsString = new String("GAME SUMMARY\n"); - // Assume 2 players for now - for(int i = 1; i <= 2; i++) { - //playerPointsString += "Player "+i+": "+gameManager.getCumulativeScores().get(i - 1)+"\n"; - playerPointsString += gameManager.getGame().getPlayer(i) +": "+gameManager.getRoundScores().get(i - 1)+"\n"; - } - - // JOptionPane.showMessageDialog(this, playerPointsString, "Game Summary", JOptionPane.PLAIN_MESSAGE); - - SummaryDialog sd = new SummaryDialog((JFrame)(mathGame.getSidePanel().getTopLevelAncestor()), "Game Summary", playerPointsString); - sd.pack(); - sd.setVisible(true); - - exit.setEnabled(true); - reset.setEnabled(true); - toggle.setEnabled(true); - if (mathGame.getUser().getPlayerID() == 1) { - // The host player deletes the game (ensuring the game is only deleted once) - GameManager.getMatchesAccess().removeGame(); - } - mathGame.showMenu(MathGame.Menu.MULTIMENU); - // Return to the multiplayer menu after the game ends - } - } - }; - waitForPlayer.start(); - } else { - // This is a solo game - - SoundManager.playSound(SoundManager.SoundType.SUCCESS); - - JOptionPane.showMessageDialog(this, "Congratulations! Victory is yours! Points earned: " + - scorekeeper.uponWinning(System.currentTimeMillis(), undo.getIndex() + 1)); - - //TODO Use sound, not dialog - //TODO Fix single player scoring system - } - - System.out.println("Cards used: " + (undo.getIndex() + 1)); - - resetFunction(); - // score.setText(Double.toString(Double.parseDouble(score.getText()) + 20)); // Determine scoring algorithm - points = (int)(scorekeeper.getTotalScore()); - score.setText(Integer.toString(points)); - } - else { - SoundManager.playSound(SoundManager.SoundType.INCORRECT); - JOptionPane.showMessageDialog(this, "Incorrect answer. Try again."); - scorekeeper.uponDeduction(1); - points = (int) scorekeeper.getTotalScore(); - score.setText(Integer.toString(points)); - } - } - - - } else { - // IF there is more than one card in the WorkPanel - JOptionPane.showMessageDialog(this, "Error. Cannot evaluate answer"); - System.out.println("ERROR.. cannot check answer for this"); - } - } else if(e.getSource() == undo) { - undoFunction(); - } else if (e.getSource() == reset) { - scorekeeper.uponDeduction(2); // Lose points for getting a new set - points = (int)(scorekeeper.getTotalScore()); - score.setText(Integer.toString(points)); - resetFunction(); - } else if (e.getSource() == exit) { - if (JOptionPane.showOptionDialog(this, + private static final long serialVersionUID = -1209424284690306920L; + + private TypeManager typeManager; + private ScoringSystem scorekeeper; + + private JLabel clock; + private JLabel score; + private JLabel vs; + + private GameButton toggle; + private GameButton help; + private GameButton exit; + private GameButton checkAns; + private UndoButton undo; + private GameButton reset; + + private static final String IMAGE_FILE = "/images/control bar.png"; + + private ImageIcon background; + + private MatchesAccess matchesAccess; + private GameManager gameManager; + + private int score1 = 0; + private int score2 = 0; + + private int correct = 0; + private int wrong = 0; + private int points = 0; + + public Timer timer; // This is public so that it can be accessed by SubMenu.java (to be started at the right time) + // StopWatch stopWatch; + + private boolean pressed = true; + + public long startTime = 0; + private long endTime = 0; + + private Insets insets = getInsets(); // Insets for the side panel for layout purposes + + public void init() { + + typeManager = MathGame.getTypeManager(); + scorekeeper = new ScoringSystem(); + gameManager = MathGame.getGameManager(); + matchesAccess = GameManager.getMatchesAccess(); + + // this.setBorder(new LineBorder(Color.BLACK)); + this.setBounds(750, 0, 150, 620); + + this.setLayout(null); + + // Instantiate controls + clock = new JLabel("00:00"); + toggle = new GameButton("Start/Stop"); + score = new JLabel("0"); + help = new GameButton("Help"); + exit = new GameButton("Back"); + checkAns = new GameButton("Check"); + undo = new UndoButton("Undo Move"); + reset = new GameButton("Reset"); + vs = new JLabel(); + + background = new ImageIcon(SidePanel.class.getResource(IMAGE_FILE)); + + add(clock); + add(toggle); + add(score); + add(help); + add(exit); + add(checkAns); + add(undo); + add(reset); + add(vs); + + // Define properties of controls + clock.setBounds(10, 10, 130, 60); + clock.setFont(MathGame.eurostile36); + clock.setHorizontalAlignment(SwingConstants.CENTER); + + score.setBounds(10, 80, 130, 60); + score.setFont(MathGame.eurostile36); + score.setHorizontalAlignment(SwingConstants.CENTER); + + toggle.setLocation(10, 150); + toggle.addActionListener(this); + + undo.setLocation(10, 190); + undo.addActionListener(this); + + reset.setLocation(10, 230); + reset.addActionListener(this); + + checkAns.setLocation(10, 270); + checkAns.addActionListener(this); + + vs.setBounds(10, 310, 130, 30); + vs.setHorizontalAlignment(SwingConstants.CENTER); + vs.setText("Vs. " + "nobody"); //TODO When versing someone, replace "nobody" with opponent name + vs.setFont(MathGame.eurostile20); + vs.setBorder(BorderFactory.createLineBorder(Color.BLACK)); + + help.setLocation(10, 540); + help.setHorizontalAlignment(SwingConstants.CENTER); + help.addActionListener(this); + + exit.setLocation(10, 580); + exit.setHorizontalAlignment(SwingConstants.CENTER); + exit.addActionListener(this); + + timer = new Timer(1000, this); + timer.setRepeats(true); + } + + public void startTimer(String type) { + timer.start(); + startTime = System.currentTimeMillis(); + scorekeeper.setGameType(type); + scorekeeper.setTimeStart(startTime); + + } + + @Override + public void paintComponent(Graphics g) { + super.paintComponents(g); + g.drawImage(background.getImage(), 0, 0, SidePanel.this); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() instanceof JButton && e.getSource() != checkAns) { // checkAns has its own sound effects + SoundManager.playSound(SoundManager.SoundType.BUTTON); + } + + if (e.getSource() == toggle) { + + if (!pressed) { + timer.start(); + startTime = System.currentTimeMillis(); + scorekeeper.setTimeStart(startTime); + pressed = true; + } else { + timer.stop(); + pressed = false; + } + } else if (e.getSource() == help) { + //TODO Decide function of Help (on website or in-game or just a hint) + //JOptionPane.showMessageDialog(this, "Instructions go here"); + GameDialogFactory.showGameMessageDialog(this, "Help", "Instructions go here", GameDialogFactory.OK); + } else if (e.getSource() == checkAns) { + if (MathGame.getWorkspacePanel().getComponentCount() == 1) { + NumberCard finalAnsCard; + Component finalAnsComp = MathGame.getWorkspacePanel().getComponent(0); + double computedAns; // The answer the user got + double actualAns; // The actual answer + if (finalAnsComp instanceof NumberCard) { + finalAnsCard = (NumberCard) finalAnsComp; + actualAns = MathGame.getCardPanel().getAns().getValue(); + computedAns = finalAnsCard.getValue(); + System.out.println(actualAns + " ?= " + computedAns); + if (actualAns - computedAns <= MathGame.epsilon) {// || + //NumberCard.parseNumFromText(actualAns) == NumberCard.parseNumFromText(computedAns)) { + // If the player's answer is right... + + if (MathGame.getGameState() == GameState.COMPETITIVE) { + // This player is done! Tell the database + points = (int) (scorekeeper.uponWinning(System.currentTimeMillis(), undo.getIndex() + 1)); + System.out.println("points: " + points); + System.out.println("gm: " + gameManager.toString()); + gameManager.updateScores(points); + + // Wait for others to finish and get score + timer.stop(); + pressed = false; + + Thread waitForPlayer = new Thread() { + public void run() { + MathGame.getCardPanel().hideCards(); // Hide cards for the next round + + System.out.println("WAIT FOR OTHER PLAYER START"); + while (!GameManager.getMatchesAccess().checkForPlayersScoresUpdated(score1, score2)) { + // Wait for other player to finish; get from database + System.out.println("waiting for other player"); + } + System.out.println("WAIT FOR OTHER PLAYER END"); + + exit.setEnabled(true); + // Temporarily enable back button in case user wants to exit + + // Display scores in round summary (for a 10 seconds) + // Figure out when it's the last round to show the total match summary (if not finished yet...) + // Meaningless statements? + gameManager.getCurrentRound(); + gameManager.getGame().getRounds(); + + System.out.println("ROUND " + gameManager.getCurrentRound() + "/" + gameManager.getGame().getRounds()); + + if (gameManager.getCurrentRound() != gameManager.getGame().getRounds()) { + String playerPointsString = "ROUND " + gameManager.getCurrentRound() + "\n"; + // Assume 2 players for now + for (int i = 1; i <= 2; i++) { + playerPointsString += gameManager.getGame().getPlayer(i) + ": " + gameManager.getRoundScores().get(i - 1) + "\n"; + } + score1 = gameManager.getRoundScores().get(0); + score2 = gameManager.getRoundScores().get(1); + System.out.println("score1 " + score1); + System.out.println("score2 " + score2); + + //Database should only be updated with the new round number once + if (MathGame.getUser().getPlayerID() == 1) { + GameManager.getMatchesAccess().incrementRound(); + } + + // JOptionPane.showMessageDialog(this, playerPointsString, "Round Summary", JOptionPane.PLAIN_MESSAGE); + System.out.println("SUMMARY DIALOG; player points: " + playerPointsString); + SummaryDialog sd = new SummaryDialog((JFrame) (MathGame.getSidePanel().getTopLevelAncestor()), "Round Summary", playerPointsString); + sd.pack(); + sd.setVisible(true); + } else { + // If this is the last match + + String playerPointsString = new String("GAME SUMMARY\n"); + // Assume 2 players for now + for (int i = 1; i <= 2; i++) { + //playerPointsString += "Player "+i+": "+gameManager.getCumulativeScores().get(i - 1)+"\n"; + playerPointsString += gameManager.getGame().getPlayer(i) + ": " + gameManager.getRoundScores().get(i - 1) + "\n"; + } + + // JOptionPane.showMessageDialog(this, playerPointsString, "Game Summary", JOptionPane.PLAIN_MESSAGE); + SummaryDialog sd = new SummaryDialog((JFrame) (MathGame.getSidePanel().getTopLevelAncestor()), "Game Summary", playerPointsString); + sd.pack(); + sd.setVisible(true); + + exit.setEnabled(true); + reset.setEnabled(true); + toggle.setEnabled(true); + if (MathGame.getUser().getPlayerID() == 1) { + // The host player deletes the game (ensuring the game is only deleted once) + GameManager.getMatchesAccess().removeGame(); + } + MathGame.showMenu(MathGame.Menu.MULTIMENU); + // Return to the multiplayer menu after the game ends + } + } + }; + waitForPlayer.start(); + } else { + // This is a solo game + + SoundManager.playSound(SoundManager.SoundType.SUCCESS); + + /*JOptionPane.showMessageDialog(this, "Congratulations! Victory is yours! Points earned: " + + scorekeeper.uponWinning(System.currentTimeMillis(), undo.getIndex() + 1));*/ + GameDialogFactory.showGameMessageDialog(this, "Congratulations!", + "Victory is yours! Points earned: " + scorekeeper.uponWinning( + System.currentTimeMillis(), undo.getIndex() + 1), GameDialogFactory.OK); + //TODO Use sound, not dialog + //TODO Fix single player scoring system + } + + System.out.println("Cards used: " + (undo.getIndex() + 1)); + + try { + resetFunction(); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + // score.setText(Double.toString(Double.parseDouble(score.getText()) + 20)); // Determine scoring algorithm + points = (int) (scorekeeper.getTotalScore()); + score.setText(Integer.toString(points)); + } else { + SoundManager.playSound(SoundManager.SoundType.INCORRECT); + //JOptionPane.showMessageDialog(this, "Incorrect answer. Try again."); + GameDialogFactory.showGameMessageDialog(this, "Sorry", + "Incorrect answer. Try again.", GameDialogFactory.OK); + scorekeeper.uponDeduction(1); + points = (int) scorekeeper.getTotalScore(); + score.setText(Integer.toString(points)); + } + } + + } else { + // IF there is more than one card in the WorkPanel + //JOptionPane.showMessageDialog(this, "Error. Cannot evaluate answer"); + GameDialogFactory.showGameMessageDialog(this, "Sorry", + "Cannot evaluate answer.", GameDialogFactory.OK); + System.out.println("ERROR.. cannot check answer for this"); + } + } else if (e.getSource() == undo) { + undoFunction(); + } else if (e.getSource() == reset) { + scorekeeper.uponDeduction(2); // Lose points for getting a new set + points = (int) (scorekeeper.getTotalScore()); + score.setText(Integer.toString(points)); + try { + resetFunction(); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } else if (e.getSource() == exit) { + /*if (JOptionPane.showOptionDialog(this, "Are you sure you want to exit?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, - null, null, null) == 0) { - if (mathGame.getGameState() == GameState.PRACTICE) { - score.setText("0.0"); // Reset the score - resetFunction(); // Reset the workspace and cardpanels - mathGame.showMenu(MathGame.Menu.MAINMENU); // Open the main menu - } else if(mathGame.getGameState() == GameState.COMPETITIVE) { - score.setText("0.0"); // Reset the score - resetFunction(); // Reset the workspace and cardpanels - mathGame.showMenu(MathGame.Menu.MULTIMENU); // Open the multiplayer menu - } - } - } - - if (timer.isRunning()) { - endTime = System.currentTimeMillis(); - clock.setText(timeFormat((int)(endTime - startTime))); - } - } - - /** - * Converts the time in milliseconds to a readable format - * - * @param millis - The number of milliseconds - * @return The time (as a string) - */ - private String timeFormat(int millis) { - // Converts from ms to s - int secs = millis / 1000; - int mins = secs / 60; - - //TODO Add hours just in case - - // Done after the calculation of minutes so that the minutes can actually increment(?) - secs %= 60; - - if (mins < 10) { - if (secs < 10) { - return ("0" + String.valueOf(mins) + ":" + "0" + String.valueOf(secs)); - } else { - return ("0" + String.valueOf(mins) + ":" + String.valueOf(secs)); - } - } else { - if (secs < 10) { - return (String.valueOf(mins) + ":" + "0" + String.valueOf(secs)); - } - else { - return (String.valueOf(mins) + ":" + String.valueOf(secs)); - } - } - } - - /** - * Carries out the undo function - */ - public void undoFunction() { - NumberCard tempnum1 = undo.getPrevNum1(); - NumberCard tempnum2 = undo.getPrevNum2(); - - // There is no need to restore the operator because it is automatically regenerated - - if (tempnum1 == null || tempnum2 == null) { - // There are no more moves (i.e. too many undos) - return; - } - - if (tempnum1.getHome() == "home") { - // The card was originally in the card panel - System.out.println("restore card1; value: " + tempnum1.getStrValue()); - mathGame.getCardPanel().restoreCard(tempnum1.getStrValue()); - } else if (tempnum1.getHome() == "hold") { - // The new card was originally in the holding area - for (int x = 0; x < mathGame.getHoldPanel().getComponentCount(); x++) { - NumberCard temp = (NumberCard)(mathGame.getHoldPanel().getComponent(0)); - if (temp.getHome() == "home") { - // Check for cards that were dragged from home into workspace and restore them - mathGame.getCardPanel().restoreCard(temp.getStrValue()); - } - } - mathGame.getHoldPanel().add(tempnum1); - } - - if (tempnum2.getHome() == "home") { - System.out.println("restore card2; value: " + tempnum2.getStrValue()); - mathGame.getCardPanel().restoreCard(tempnum2.getStrValue()); - } else if (tempnum2.getHome() == "hold") { - for (int x = 0; x < mathGame.getHoldPanel().getComponentCount(); x++) { - NumberCard temp = (NumberCard)(mathGame.getHoldPanel().getComponent(0)); - if (temp.getHome() == "home") { - mathGame.getCardPanel().restoreCard(temp.getStrValue()); - } - } - mathGame.getHoldPanel().add(tempnum2); - } - - if (mathGame.getWorkspacePanel().getComponentCount() == 0) { - // Covers the scenario in which the previously-created card was put in the holding area - - NumberCard prevAns = undo.getPrevNewNum(); // Holds the previously-calculated answer - - NumberCard temp; - - // Cycle through cards in hold - for (int i = 0; i < mathGame.getHoldPanel().getComponentCount(); i++) { - temp = (NumberCard)(mathGame.getHoldPanel().getComponent(i)); - // The explicit casting assumes that only NumberCards will be in holdpanel - - if (temp.getStrValue() == prevAns.getStrValue()) { - // See if the checked card is the previous answer - System.out.println("Deleting card in hold"); - mathGame.getHoldPanel().remove(i); - i = mathGame.getHoldPanel().getComponentCount() + 1; // So we can exit this loop (Why not use a break?) - } - } - } else { - // Covers the scenario in which the previously-created card is still in the work panel - - NumberCard prevAns = undo.getPrevNewNum(); // Holds the previously-calculated answer - - NumberCard temp; - - // Cycle through cards in workspace - for (int i = 0; i < mathGame.getWorkspacePanel().getComponentCount(); i++) { - if (mathGame.getWorkspacePanel().getComponent(i) instanceof NumberCard) { - temp = (NumberCard)(mathGame.getWorkspacePanel().getComponent(i)); - if (temp.getValue() == prevAns.getValue()) { - // See if the checked card is the previous answer - mathGame.getWorkspacePanel().remove(i); - i = mathGame.getWorkspacePanel().getComponentCount() + 1; // So we can exit this loop (Why not just break?) - } - } - } - } - - undo.completeUndo(); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getWorkspacePanel().repaint(); - mathGame.getHoldPanel().revalidate(); - mathGame.getHoldPanel().repaint(); - mathGame.getCardPanel().revalidate(); - } - - /** - * Carries out the reset function - */ - private void resetFunction() { - timer.stop(); - - mathGame.getCardPanel().resetValidationBoxes(); - - while (undo.getIndex() > 0) { - undoFunction(); - } - - scorekeeper.setTimeStart(System.currentTimeMillis()); - - if (mathGame.getWorkspacePanel().getComponentCount() > 0) { - NumberCard temp; - OperationCard temp2; - int count = mathGame.getWorkspacePanel().getComponentCount(); - for (int x = 0; x < count; x++) { - if (mathGame.getWorkspacePanel().getComponent(0) instanceof NumberCard) { - temp = (NumberCard)(mathGame.getWorkspacePanel().getComponent(0)); - mathGame.getCardPanel().restoreCard(temp.getStrValue()); - } else if (mathGame.getWorkspacePanel().getComponent(0) instanceof OperationCard) { - temp2 = (OperationCard)(mathGame.getWorkspacePanel().getComponent(0)); - mathGame.getOperationPanel().addOperator(temp2.getOperation()); - } - } - } - - if (mathGame.getHoldPanel().getComponentCount() > 0) { - NumberCard temp; - OperationCard temp2; - int count = mathGame.getHoldPanel().getComponentCount(); - for (int x = 0; x < count; x++) { - if (mathGame.getHoldPanel().getComponent(0) instanceof NumberCard) { - temp = (NumberCard)(mathGame.getHoldPanel().getComponent(0)); - mathGame.getCardPanel().restoreCard(temp.getStrValue()); - } else if (mathGame.getHoldPanel().getComponent(0) instanceof OperationCard) { - temp2 = (OperationCard)(mathGame.getHoldPanel().getComponent(0)); - mathGame.getOperationPanel().addOperator(temp2.getOperation()); - } - } - } - - typeManager.randomize(); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getWorkspacePanel().repaint(); - mathGame.getHoldPanel().revalidate(); - mathGame.getHoldPanel().repaint(); - mathGame.getCardPanel().revalidate(); - - timer.start(); - startTime = System.currentTimeMillis(); - } - - /** - * Sets up the multiplayer environment (disabling buttons) - */ - public void setUpMultiplayer() { - exit.setEnabled(false); - reset.setEnabled(false); - toggle.setEnabled(false); - //TODO Display the opponent's name - } - - /** - * The SummaryDialog class is designed for displaying the summary of a round or a game - */ - class SummaryDialog extends JDialog implements ActionListener { - - private static final long serialVersionUID = -5238902054895186832L; - - JOptionPane option; - JLabel count; - JLabel playerPoints; - - public SummaryDialog(JFrame frame, String title, String text) { - super(frame, true); - playerPoints = new JLabel(text); - count = new JLabel("00:10"); - Object items[] = {text, count}; - option = new JOptionPane(items, JOptionPane.PLAIN_MESSAGE, JOptionPane.CANCEL_OPTION, null, null); - setContentPane(option); - setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - - Timer timer1 = new Timer(10000, this); - timer1.addActionListener(this); - timer1.setRepeats(false); - - timer.stop(); - startTime = System.currentTimeMillis(); - timer1.start(); - timer.start(); - - Thread dialogTimer = new Thread() { - public void run() { - while (timer.isRunning()) { - endTime = System.currentTimeMillis(); - count.setText(timeFormat((int)(10000 - (endTime - startTime)))); - } - } - }; - - dialogTimer.start(); - - if(isDisplayable()) { - setVisible(true); - } - } - - @Override - public void actionPerformed(ActionEvent arg0) { - System.out.println("CLOSE DIALOG"); - - exit.setEnabled(false); // Set back to disabled when the dialog is finished - mathGame.getCardPanel().showCards(); // Now you can show the cards! - - timer.stop(); // Stop timer from previous thread - - timer.start(); // Restart timer - - startTime = System.currentTimeMillis(); - scorekeeper.setTimeStart(startTime); - - pressed = true; - - this.setVisible(false); - this.dispose(); // Destroy this dialog - } - } + null, null, null) == 0) {*/ + if (GameDialogFactory.showGameOptionDialog(this, "Exit", "Are you sure you want to exit?") == 0) { + score.setText("0.0"); // Reset the score + exit.setEnabled(true); + + try { + resetFunction(); + + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } // Reset the workspace and cardpanels + if (MathGame.getUser().getPlayerID() == 1) { + // The host player deletes the game (ensuring the game is only deleted once) + GameManager.getMatchesAccess().removeGame(); + } + + MathGame.showMenu(MathGame.Menu.MULTIMENU); // Open the multiplayer menu + } + } + + if (timer.isRunning()) { + endTime = System.currentTimeMillis(); + clock.setText(timeFormat((int) (endTime - startTime))); + } + } + + /** + * Converts the time in milliseconds to a readable format + * + * @param millis - The number of milliseconds + * @return The time (as a string) + */ + private String timeFormat(int millis) { + // Converts from ms to s + int secs = millis / 1000; + int mins = secs / 60; + + //TODO Add hours just in case + // Done after the calculation of minutes so that the minutes can actually increment(?) + secs %= 60; + + if (mins < 10) { + if (secs < 10) { + return ("0" + String.valueOf(mins) + ":" + "0" + String.valueOf(secs)); + } else { + return ("0" + String.valueOf(mins) + ":" + String.valueOf(secs)); + } + } else if (secs < 10) { + return (String.valueOf(mins) + ":" + "0" + String.valueOf(secs)); + } else { + return (String.valueOf(mins) + ":" + String.valueOf(secs)); + } + } + + /** + * Carries out the undo function + */ + public void undoFunction() { + NumberCard tempnum1 = undo.getPrevNum1(); + NumberCard tempnum2 = undo.getPrevNum2(); + + // There is no need to restore the operator because it is automatically regenerated + if (tempnum1 == null || tempnum2 == null) { + // There are no more moves (i.e. too many undos) + return; + } + + if (tempnum1.getHome() == "home") { + // The card was originally in the card panel + System.out.println("restore card1; value: " + tempnum1.getStrValue()); + MathGame.getCardPanel().restoreCard(tempnum1.getStrValue()); + } else if (tempnum1.getHome() == "hold") { + // The new card was originally in the holding area + for (int x = 0; x < MathGame.getHoldPanel().getComponentCount(); x++) { + NumberCard temp = (NumberCard) (MathGame.getHoldPanel().getComponent(0)); + if (temp.getHome() == "home") { + // Check for cards that were dragged from home into workspace and restore them + MathGame.getCardPanel().restoreCard(temp.getStrValue()); + } + } + MathGame.getHoldPanel().add(tempnum1); + } + + if (tempnum2.getHome() == "home") { + System.out.println("restore card2; value: " + tempnum2.getStrValue()); + MathGame.getCardPanel().restoreCard(tempnum2.getStrValue()); + } else if (tempnum2.getHome() == "hold") { + for (int x = 0; x < MathGame.getHoldPanel().getComponentCount(); x++) { + NumberCard temp = (NumberCard) (MathGame.getHoldPanel().getComponent(0)); + if (temp.getHome() == "home") { + MathGame.getCardPanel().restoreCard(temp.getStrValue()); + } + } + MathGame.getHoldPanel().add(tempnum2); + } + + if (MathGame.getWorkspacePanel().getComponentCount() == 0) { + // Covers the scenario in which the previously-created card was put in the holding area + + NumberCard prevAns = undo.getPrevNewNum(); // Holds the previously-calculated answer + + NumberCard temp; + + // Cycle through cards in hold + for (int i = 0; i < MathGame.getHoldPanel().getComponentCount(); i++) { + temp = (NumberCard) (MathGame.getHoldPanel().getComponent(i)); + // The explicit casting assumes that only NumberCards will be in holdpanel + + if (temp.getStrValue() == prevAns.getStrValue()) { + // See if the checked card is the previous answer + System.out.println("Deleting card in hold"); + MathGame.getHoldPanel().remove(i); + i = MathGame.getHoldPanel().getComponentCount() + 1; // So we can exit this loop (Why not use a break?) + } + } + } else { + // Covers the scenario in which the previously-created card is still in the work panel + + NumberCard prevAns = undo.getPrevNewNum(); // Holds the previously-calculated answer + + NumberCard temp; + + // Cycle through cards in workspace + for (int i = 0; i < MathGame.getWorkspacePanel().getComponentCount(); i++) { + if (MathGame.getWorkspacePanel().getComponent(i) instanceof NumberCard) { + temp = (NumberCard) (MathGame.getWorkspacePanel().getComponent(i)); + if (temp.getValue() == prevAns.getValue()) { + // See if the checked card is the previous answer + MathGame.getWorkspacePanel().remove(i); + i = MathGame.getWorkspacePanel().getComponentCount() + 1; // So we can exit this loop (Why not just break?) + } + } + } + } + + undo.completeUndo(); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getWorkspacePanel().repaint(); + MathGame.getHoldPanel().revalidate(); + MathGame.getHoldPanel().repaint(); + MathGame.getCardPanel().revalidate(); + } + + /** + * Carries out the reset function + * + * @throws Exception + */ + private void resetFunction() throws Exception { + timer.stop(); + + MathGame.getCardPanel().resetValidationBoxes(); + + while (undo.getIndex() > 0) { + undoFunction(); + } + + scorekeeper.setTimeStart(System.currentTimeMillis()); + + if (MathGame.getWorkspacePanel().getComponentCount() > 0) { + NumberCard temp; + OperationCard temp2; + int count = MathGame.getWorkspacePanel().getComponentCount(); + for (int x = 0; x < count; x++) { + if (MathGame.getWorkspacePanel().getComponent(0) instanceof NumberCard) { + temp = (NumberCard) (MathGame.getWorkspacePanel().getComponent(0)); + MathGame.getCardPanel().restoreCard(temp.getStrValue()); + } else if (MathGame.getWorkspacePanel().getComponent(0) instanceof OperationCard) { + temp2 = (OperationCard) (MathGame.getWorkspacePanel().getComponent(0)); + MathGame.getOperationPanel().addOperator(temp2.getOperation()); + } + } + } + + if (MathGame.getHoldPanel().getComponentCount() > 0) { + NumberCard temp; + OperationCard temp2; + int count = MathGame.getHoldPanel().getComponentCount(); + for (int x = 0; x < count; x++) { + if (MathGame.getHoldPanel().getComponent(0) instanceof NumberCard) { + temp = (NumberCard) (MathGame.getHoldPanel().getComponent(0)); + MathGame.getCardPanel().restoreCard(temp.getStrValue()); + } else if (MathGame.getHoldPanel().getComponent(0) instanceof OperationCard) { + temp2 = (OperationCard) (MathGame.getHoldPanel().getComponent(0)); + MathGame.getOperationPanel().addOperator(temp2.getOperation()); + } + } + } + + typeManager.randomize(); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getWorkspacePanel().repaint(); + MathGame.getHoldPanel().revalidate(); + MathGame.getHoldPanel().repaint(); + MathGame.getCardPanel().revalidate(); + + timer.start(); + startTime = System.currentTimeMillis(); + } + + /** + * Sets up the multiplayer environment (disabling buttons) + */ + public void setUpMultiplayer() { + exit.setEnabled(false); + reset.setEnabled(false); + toggle.setEnabled(false); + //TODO Display the opponent's name + } + + /** + * @return the undo + */ + public UndoButton getUndo() { + return undo; + } + + /** + * The SummaryDialog class is designed for displaying the summary of a round + * or a game + */ + class SummaryDialog extends JDialog implements ActionListener { + + private static final long serialVersionUID = -5238902054895186832L; + + private JOptionPane option; + private JLabel count; + private JLabel playerPoints; + + public SummaryDialog(JFrame frame, String title, String text) { + super((JFrame) MathGame.getWorkspacePanel().getTopLevelAncestor(), true);//uses the JFrame + playerPoints = new JLabel(text); + count = new JLabel("00:10"); + count.setFont(MathGame.eurostile16); + Object items[] = {text, count}; + option = new JOptionPane(items, JOptionPane.PLAIN_MESSAGE, JOptionPane.CANCEL_OPTION, null, null); + setContentPane(option); + setLocationRelativeTo(null);//centers dialog on screen + setAutoRequestFocus(true);//puts dialog on top (focused) + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + + Timer timer1 = new Timer(10000, this); + timer1.addActionListener(this); + timer1.setRepeats(false); + + timer.stop(); + startTime = System.currentTimeMillis(); + timer1.start(); + timer.start(); + + Thread dialogTimer = new Thread() { + public void run() { + while (timer.isRunning()) { + endTime = System.currentTimeMillis(); + count.setText(timeFormat((int) (10000 - (endTime - startTime)))); + } + } + }; + + dialogTimer.start(); + + if (isDisplayable()) { + setVisible(true); + } + } + + @Override + public void actionPerformed(ActionEvent arg0) { + System.out.println("CLOSE DIALOG"); + + exit.setEnabled(false); // Set back to disabled when the dialog is finished + MathGame.getCardPanel().showCards(); // Now you can show the cards! + + timer.stop(); // Stop timer from previous thread + + timer.start(); // Restart timer + + startTime = System.currentTimeMillis(); + scorekeeper.setTimeStart(startTime); + + pressed = true; + + this.setVisible(false); + this.dispose(); // Destroy this dialog + } + } } diff --git a/src/com/mathgame/panels/WorkspacePanel.java b/src/com/mathgame/panels/WorkspacePanel.java index edfe8e3..6b6cc9f 100644 --- a/src/com/mathgame/panels/WorkspacePanel.java +++ b/src/com/mathgame/panels/WorkspacePanel.java @@ -24,6 +24,8 @@ import com.mathgame.cards.NumberCard; import com.mathgame.cards.OperationCard; +import com.mathgame.guicomponents.GameButton; +import com.mathgame.guicomponents.GameDialogFactory; import com.mathgame.math.Calculate; import com.mathgame.math.CompMover; import com.mathgame.math.MathGame; @@ -39,16 +41,14 @@ public class WorkspacePanel extends JPanel { private static final long serialVersionUID = 7408931441173570326L; - static MathGame mathGame; - private static final String IMAGE_FILE = "/images/Workspace.png"; - ImageIcon background; + private ImageIcon background; - CompMover mover; - TypeManager typeManager; + private CompMover mover; + private TypeManager typeManager; - public void init(MathGame mathGame) { + public void init() { this.setLayout(new FlowLayout()); Border empty = BorderFactory.createEmptyBorder(70,70,70,70); @@ -60,13 +60,11 @@ public void init(MathGame mathGame) { size.height = 260; setPreferredSize(size); - // background = mathGame.getImage(mathGame.getDocumentBase(), imageFile); background = new ImageIcon(WorkspacePanel.class.getResource(IMAGE_FILE)); - mover = new CompMover(); + mover = MathGame.getCompMover(); - WorkspacePanel.mathGame = mathGame; - typeManager = mathGame.getTypeManager(); + typeManager = MathGame.getTypeManager(); } /** @@ -78,7 +76,7 @@ public void calcCheck() { Double answer = null; if (count == 3) { - answer = Calculate.calculate(this.getComponent(0), this.getComponent(1), this.getComponent(2), mathGame); + answer = Calculate.calculate(this.getComponent(0), this.getComponent(1), this.getComponent(2)); } if (answer != null) { @@ -89,65 +87,65 @@ public void calcCheck() { NumberCard tempnum1 = (NumberCard)(this.getComponent(0)); NumberCard tempnum2 = (NumberCard)(this.getComponent(2)); - mathGame.getOperationPanel().addOperator(currentOperation()); + MathGame.getOperationPanel().addOperator(currentOperation()); if (tempnum1.getHome() == "home") { // The card was originally in the card panel System.out.println("restore card1; value: " + tempnum1.getStrValue()); - mathGame.getCardPanel().restoreCard(tempnum1.getStrValue()); + MathGame.getCardPanel().restoreCard(tempnum1.getStrValue()); } else if (tempnum1.getHome() == "hold") { // The card was originally in the holding area - for (int x = 0; x < mathGame.getHoldPanel().getComponentCount(); x++) { - NumberCard temp = (NumberCard)(mathGame.getHoldPanel().getComponent(0)); + for (int x = 0; x < MathGame.getHoldPanel().getComponentCount(); x++) { + NumberCard temp = (NumberCard)(MathGame.getHoldPanel().getComponent(0)); if (temp.getHome() == "home") { // Check for cards that were dragged from home into workspace and restore them - mathGame.getCardPanel().restoreCard(temp.getStrValue()); + MathGame.getCardPanel().restoreCard(temp.getStrValue()); } } - mathGame.getHoldPanel().add(tempnum1); + MathGame.getHoldPanel().add(tempnum1); } if (tempnum2.getHome() == "home") { System.out.println("restore card2; value: " + tempnum2.getStrValue()); - mathGame.getCardPanel().restoreCard(tempnum2.getStrValue()); + MathGame.getCardPanel().restoreCard(tempnum2.getStrValue()); } else if (tempnum2.getHome() == "hold") { - for (int x = 0; x < mathGame.getHoldPanel().getComponentCount(); x++) { - NumberCard temp = (NumberCard)(mathGame.getHoldPanel().getComponent(0)); + for (int x = 0; x < MathGame.getHoldPanel().getComponentCount(); x++) { + NumberCard temp = (NumberCard)(MathGame.getHoldPanel().getComponent(0)); if (temp.getHome() == "home") { - mathGame.getCardPanel().restoreCard(temp.getStrValue()); + MathGame.getCardPanel().restoreCard(temp.getStrValue()); } } - mathGame.getHoldPanel().add(tempnum2); + MathGame.getHoldPanel().add(tempnum2); } else { System.out.println("HELP"); } this.removeAll(); - mathGame.getWorkspacePanel().revalidate(); - mathGame.getWorkspacePanel().repaint(); - mathGame.getHoldPanel().revalidate(); - mathGame.getHoldPanel().repaint(); - mathGame.getCardPanel().revalidate(); + MathGame.getWorkspacePanel().revalidate(); + MathGame.getWorkspacePanel().repaint(); + MathGame.getHoldPanel().revalidate(); + MathGame.getHoldPanel().repaint(); + MathGame.getCardPanel().revalidate(); return; } boolean ansState = true; // In practice mode, the user must evaluate the answer too - if(mathGame.getGameState() == GameState.PRACTICE) { + if(MathGame.getGameState() == GameState.PRACTICE) { ansState = askAnswer(answer); } NumberCard answerCard = new NumberCard(answer); - if (typeManager.getType() == GameType.FRACTIONS) { + if (typeManager.getType().contains(GameType.FRACTIONS)) { String temp = TypeManager.convertDecimaltoFraction(answer); - answerCard.setValue(temp); + answerCard.setValue(answer); answerCard.setStrValue(temp); System.out.println("as fraction: " + TypeManager.convertDecimaltoFraction(answer)); } else { - answerCard.setValue(""+answer); + answerCard.setValue(answer); } answerCard.addMouseListener(mover); @@ -163,12 +161,12 @@ public void calcCheck() { NumberCard card2 = (NumberCard) this.getComponent(2); OperationCard op = (OperationCard) this.getComponent(1); System.out.println("Registering new Move"); - mathGame.getSidePanel().undo.registerNewMove(card1, op, card2, answerCard); + MathGame.getSidePanel().getUndo().registerNewMove(card1, op, card2, answerCard); // When cards collide... it becomes a new move! } } - mathGame.getOperationPanel().addOperator(currentOperation()); + MathGame.getOperationPanel().addOperator(currentOperation()); System.out.println("NUM:" + this.getComponentCount()); this.removeAll(); @@ -177,7 +175,7 @@ public void calcCheck() { if (!ansState) { // If false, undo (this means user cancelled inputting function) - mathGame.getSidePanel().undoFunction(); + MathGame.getSidePanel().undoFunction(); } // System.out.println(answerCard.getParent()); @@ -259,11 +257,11 @@ class AnswerDialog extends JDialog implements ActionListener { private static final long serialVersionUID = -8292422603267484832L; - private String input; // What the user inputs as the answe + private String input; // What the user inputs as the answer private String equation; // The equation to display private Double answer; // The answer to the equation private JTextField text; - private JButton cancel; + private GameButton cancel; private JPanel panel; private JLabel incorrect; private boolean isCorrect; @@ -274,20 +272,26 @@ class AnswerDialog extends JDialog implements ActionListener { * @param equation - The equation to display */ public AnswerDialog(JFrame fr, Double answer, String equation) { - super(fr, true); + super((JFrame)MathGame.getWorkspacePanel().getTopLevelAncestor(), true);//uses the JFrame this.answer = answer; this.equation = equation; text = new JTextField(10); // Size 10 font + text.setFont(MathGame.eurostile16); text.addActionListener(this); incorrect = new JLabel("Incorrect"); + incorrect.setFont(MathGame.eurostile16); - cancel = new JButton("Cancel"); + cancel = new GameButton("Cancel"); cancel.addActionListener(this); + JLabel eqLabel = new JLabel(this.equation); + eqLabel.setFont(MathGame.eurostile16); + panel = new JPanel(); - panel.add(new JLabel(this.equation)); + panel.setBackground(MathGame.offWhite); + panel.add(eqLabel); panel.add(text); panel.add(incorrect); panel.add(cancel); @@ -295,7 +299,8 @@ public AnswerDialog(JFrame fr, Double answer, String equation) { incorrect.setVisible(false); setContentPane(panel); - setAutoRequestFocus(true); + setLocationRelativeTo(null);//centers dialog on screen + setAutoRequestFocus(true);//puts dialog on top (focused) /* addWindowListener(new WindowAdapter() { diff --git a/src/images/DefaultButtonImage1.png b/src/images/DefaultButtonImage1.png index b546c94..5ffea18 100644 Binary files a/src/images/DefaultButtonImage1.png and b/src/images/DefaultButtonImage1.png differ diff --git a/src/images/DefaultButtonImage2.png b/src/images/DefaultButtonImage2.png index 75b1fa7..b5d96c9 100644 Binary files a/src/images/DefaultButtonImage2.png and b/src/images/DefaultButtonImage2.png differ diff --git a/src/images/DefaultButtonImage3.png b/src/images/DefaultButtonImage3.png index 3c5f34c..6ada89f 100644 Binary files a/src/images/DefaultButtonImage3.png and b/src/images/DefaultButtonImage3.png differ diff --git a/src/images/MenuButtonImg1.png b/src/images/MenuButtonImg1.png deleted file mode 100644 index bb39ddd..0000000 Binary files a/src/images/MenuButtonImg1.png and /dev/null differ diff --git a/src/images/MenuButtonImg2.png b/src/images/MenuButtonImg2.png deleted file mode 100644 index 75b1fa7..0000000 Binary files a/src/images/MenuButtonImg2.png and /dev/null differ diff --git a/src/images/MenuButtonImg3.png b/src/images/MenuButtonImg3.png deleted file mode 100644 index 3c5f34c..0000000 Binary files a/src/images/MenuButtonImg3.png and /dev/null differ diff --git a/src/images/Screenshots/class1.jpg b/src/images/Screenshots/class1.jpg new file mode 100644 index 0000000..05696d6 Binary files /dev/null and b/src/images/Screenshots/class1.jpg differ diff --git a/src/images/Screenshots/class2.jpg b/src/images/Screenshots/class2.jpg new file mode 100644 index 0000000..2cfff92 Binary files /dev/null and b/src/images/Screenshots/class2.jpg differ diff --git a/src/images/Screenshots/gameplay.png b/src/images/Screenshots/gameplay.png new file mode 100644 index 0000000..4e975f1 Binary files /dev/null and b/src/images/Screenshots/gameplay.png differ diff --git a/src/images/Screenshots/gamesettings.png b/src/images/Screenshots/gamesettings.png new file mode 100644 index 0000000..4f47301 Binary files /dev/null and b/src/images/Screenshots/gamesettings.png differ diff --git a/src/images/Screenshots/login.jpg b/src/images/Screenshots/login.jpg new file mode 100644 index 0000000..c1e2655 Binary files /dev/null and b/src/images/Screenshots/login.jpg differ diff --git a/src/images/Screenshots/menu.jpg b/src/images/Screenshots/menu.jpg new file mode 100644 index 0000000..c63dd9c Binary files /dev/null and b/src/images/Screenshots/menu.jpg differ diff --git a/src/images/Thumbs.db b/src/images/Thumbs.db index 32d8f46..35c8e6f 100644 Binary files a/src/images/Thumbs.db and b/src/images/Thumbs.db differ diff --git a/src/images/backMulti.png b/src/images/backMulti.png index 550c97e..a52865d 100644 Binary files a/src/images/backMulti.png and b/src/images/backMulti.png differ diff --git a/src/images/backa.png b/src/images/backa.png index 00d7950..c2a6de8 100644 Binary files a/src/images/backa.png and b/src/images/backa.png differ diff --git a/src/images/backb.png b/src/images/backb.png new file mode 100644 index 0000000..d9d9039 Binary files /dev/null and b/src/images/backb.png differ diff --git a/src/images/background2.png b/src/images/background2.png index 550c97e..a52865d 100644 Binary files a/src/images/background2.png and b/src/images/background2.png differ diff --git a/src/images/buttonRollovver.png b/src/images/buttonRollovver.png deleted file mode 100644 index 2af0b4d..0000000 Binary files a/src/images/buttonRollovver.png and /dev/null differ diff --git a/src/images/buttonStandard.png b/src/images/buttonStandard.png deleted file mode 100644 index eabd6a8..0000000 Binary files a/src/images/buttonStandard.png and /dev/null differ diff --git a/src/images/exponent.png b/src/images/exponent.png new file mode 100644 index 0000000..a8f566f Binary files /dev/null and b/src/images/exponent.png differ diff --git a/src/images/mute.png b/src/images/mute.png index 00f215b..6d84106 100644 Binary files a/src/images/mute.png and b/src/images/mute.png differ diff --git a/src/images/refreshButton.png b/src/images/refreshButton.png deleted file mode 100644 index 1fdf4ef..0000000 Binary files a/src/images/refreshButton.png and /dev/null differ diff --git a/src/images/refresnButtonRollover.png b/src/images/refresnButtonRollover.png deleted file mode 100644 index 794e94c..0000000 Binary files a/src/images/refresnButtonRollover.png and /dev/null differ diff --git a/src/images/sound.png b/src/images/sound.png index 26c08c2..fc4203b 100644 Binary files a/src/images/sound.png and b/src/images/sound.png differ diff --git a/src/spreadsheets/Decimals.xlsx b/src/spreadsheets/Decimals.xlsx new file mode 100644 index 0000000..628bfc4 Binary files /dev/null and b/src/spreadsheets/Decimals.xlsx differ diff --git a/src/spreadsheets/Decimals_Easy.xlsx b/src/spreadsheets/Decimals_Easy.xlsx new file mode 100644 index 0000000..34bf002 Binary files /dev/null and b/src/spreadsheets/Decimals_Easy.xlsx differ diff --git a/src/spreadsheets/Decimals_Hard.xlsx b/src/spreadsheets/Decimals_Hard.xlsx new file mode 100644 index 0000000..01c1d43 Binary files /dev/null and b/src/spreadsheets/Decimals_Hard.xlsx differ diff --git a/src/spreadsheets/Decimals_Medium.xlsx b/src/spreadsheets/Decimals_Medium.xlsx new file mode 100644 index 0000000..8e46e4f Binary files /dev/null and b/src/spreadsheets/Decimals_Medium.xlsx differ diff --git a/src/spreadsheets/Exponents.xlsx b/src/spreadsheets/Exponents.xlsx new file mode 100644 index 0000000..1c4a268 Binary files /dev/null and b/src/spreadsheets/Exponents.xlsx differ diff --git a/src/spreadsheets/Fractions.xlsx b/src/spreadsheets/Fractions.xlsx new file mode 100644 index 0000000..583a844 Binary files /dev/null and b/src/spreadsheets/Fractions.xlsx differ diff --git a/src/spreadsheets/Fractions_Easy.xlsx b/src/spreadsheets/Fractions_Easy.xlsx new file mode 100644 index 0000000..51aa0a7 Binary files /dev/null and b/src/spreadsheets/Fractions_Easy.xlsx differ diff --git a/src/spreadsheets/Fractions_Hard.xlsx b/src/spreadsheets/Fractions_Hard.xlsx new file mode 100644 index 0000000..3171724 Binary files /dev/null and b/src/spreadsheets/Fractions_Hard.xlsx differ diff --git a/src/spreadsheets/Fractions_Medium.xlsx b/src/spreadsheets/Fractions_Medium.xlsx new file mode 100644 index 0000000..2d4873c Binary files /dev/null and b/src/spreadsheets/Fractions_Medium.xlsx differ diff --git a/src/spreadsheets/Integers.xlsx b/src/spreadsheets/Integers.xlsx new file mode 100644 index 0000000..87308ea Binary files /dev/null and b/src/spreadsheets/Integers.xlsx differ diff --git a/src/spreadsheets/Logarithms.xlsx b/src/spreadsheets/Logarithms.xlsx new file mode 100644 index 0000000..7400a24 Binary files /dev/null and b/src/spreadsheets/Logarithms.xlsx differ