Copy disabled (too large)
Download .txt
Showing preview only (39,136K chars total). Download the full file to get everything.
Repository: molson194/Artificial-Intelligence-Berkeley-CS188
Branch: master
Commit: 3291b48c29bd
Files: 671
Total size: 59.2 MB
Directory structure:
gitextract_015yh1ta/
├── Project-1/
│ ├── VERSION
│ ├── autograder.py
│ ├── commands.txt
│ ├── eightpuzzle.py
│ ├── game.py
│ ├── ghostAgents.py
│ ├── grading.py
│ ├── graphicsDisplay.py
│ ├── graphicsUtils.py
│ ├── keyboardAgents.py
│ ├── layout.py
│ ├── layouts/
│ │ ├── bigCorners.lay
│ │ ├── bigMaze.lay
│ │ ├── bigSafeSearch.lay
│ │ ├── bigSearch.lay
│ │ ├── boxSearch.lay
│ │ ├── capsuleClassic.lay
│ │ ├── contestClassic.lay
│ │ ├── contoursMaze.lay
│ │ ├── greedySearch.lay
│ │ ├── mediumClassic.lay
│ │ ├── mediumCorners.lay
│ │ ├── mediumDottedMaze.lay
│ │ ├── mediumMaze.lay
│ │ ├── mediumSafeSearch.lay
│ │ ├── mediumScaryMaze.lay
│ │ ├── mediumSearch.lay
│ │ ├── minimaxClassic.lay
│ │ ├── oddSearch.lay
│ │ ├── openClassic.lay
│ │ ├── openMaze.lay
│ │ ├── openSearch.lay
│ │ ├── originalClassic.lay
│ │ ├── smallClassic.lay
│ │ ├── smallMaze.lay
│ │ ├── smallSafeSearch.lay
│ │ ├── smallSearch.lay
│ │ ├── testClassic.lay
│ │ ├── testMaze.lay
│ │ ├── testSearch.lay
│ │ ├── tinyCorners.lay
│ │ ├── tinyMaze.lay
│ │ ├── tinySafeSearch.lay
│ │ ├── tinySearch.lay
│ │ ├── trappedClassic.lay
│ │ ├── trickyClassic.lay
│ │ └── trickySearch.lay
│ ├── pacman.py
│ ├── pacmanAgents.py
│ ├── projectParams.py
│ ├── search.py
│ ├── searchAgents.py
│ ├── searchTestClasses.py
│ ├── testClasses.py
│ ├── testParser.py
│ ├── test_cases/
│ │ ├── CONFIG
│ │ ├── q1/
│ │ │ ├── CONFIG
│ │ │ ├── graph_backtrack.solution
│ │ │ ├── graph_backtrack.test
│ │ │ ├── graph_bfs_vs_dfs.solution
│ │ │ ├── graph_bfs_vs_dfs.test
│ │ │ ├── graph_infinite.solution
│ │ │ ├── graph_infinite.test
│ │ │ ├── graph_manypaths.solution
│ │ │ ├── graph_manypaths.test
│ │ │ ├── pacman_1.solution
│ │ │ └── pacman_1.test
│ │ ├── q2/
│ │ │ ├── CONFIG
│ │ │ ├── graph_backtrack.solution
│ │ │ ├── graph_backtrack.test
│ │ │ ├── graph_bfs_vs_dfs.solution
│ │ │ ├── graph_bfs_vs_dfs.test
│ │ │ ├── graph_infinite.solution
│ │ │ ├── graph_infinite.test
│ │ │ ├── graph_manypaths.solution
│ │ │ ├── graph_manypaths.test
│ │ │ ├── pacman_1.solution
│ │ │ └── pacman_1.test
│ │ ├── q3/
│ │ │ ├── CONFIG
│ │ │ ├── graph_backtrack.solution
│ │ │ ├── graph_backtrack.test
│ │ │ ├── graph_bfs_vs_dfs.solution
│ │ │ ├── graph_bfs_vs_dfs.test
│ │ │ ├── graph_infinite.solution
│ │ │ ├── graph_infinite.test
│ │ │ ├── graph_manypaths.solution
│ │ │ ├── graph_manypaths.test
│ │ │ ├── ucs_0_graph.solution
│ │ │ ├── ucs_0_graph.test
│ │ │ ├── ucs_1_problemC.solution
│ │ │ ├── ucs_1_problemC.test
│ │ │ ├── ucs_2_problemE.solution
│ │ │ ├── ucs_2_problemE.test
│ │ │ ├── ucs_3_problemW.solution
│ │ │ ├── ucs_3_problemW.test
│ │ │ ├── ucs_4_testSearch.solution
│ │ │ ├── ucs_4_testSearch.test
│ │ │ ├── ucs_5_goalAtDequeue.solution
│ │ │ └── ucs_5_goalAtDequeue.test
│ │ ├── q4/
│ │ │ ├── CONFIG
│ │ │ ├── astar_0.solution
│ │ │ ├── astar_0.test
│ │ │ ├── astar_1_graph_heuristic.solution
│ │ │ ├── astar_1_graph_heuristic.test
│ │ │ ├── astar_2_manhattan.solution
│ │ │ ├── astar_2_manhattan.test
│ │ │ ├── astar_3_goalAtDequeue.solution
│ │ │ ├── astar_3_goalAtDequeue.test
│ │ │ ├── graph_backtrack.solution
│ │ │ ├── graph_backtrack.test
│ │ │ ├── graph_manypaths.solution
│ │ │ └── graph_manypaths.test
│ │ ├── q5/
│ │ │ ├── CONFIG
│ │ │ ├── corner_tiny_corner.solution
│ │ │ └── corner_tiny_corner.test
│ │ ├── q6/
│ │ │ ├── CONFIG
│ │ │ ├── corner_sanity_1.solution
│ │ │ ├── corner_sanity_1.test
│ │ │ ├── corner_sanity_2.solution
│ │ │ ├── corner_sanity_2.test
│ │ │ ├── corner_sanity_3.solution
│ │ │ ├── corner_sanity_3.test
│ │ │ ├── medium_corners.solution
│ │ │ └── medium_corners.test
│ │ ├── q7/
│ │ │ ├── CONFIG
│ │ │ ├── food_heuristic_1.solution
│ │ │ ├── food_heuristic_1.test
│ │ │ ├── food_heuristic_10.solution
│ │ │ ├── food_heuristic_10.test
│ │ │ ├── food_heuristic_11.solution
│ │ │ ├── food_heuristic_11.test
│ │ │ ├── food_heuristic_12.solution
│ │ │ ├── food_heuristic_12.test
│ │ │ ├── food_heuristic_13.solution
│ │ │ ├── food_heuristic_13.test
│ │ │ ├── food_heuristic_14.solution
│ │ │ ├── food_heuristic_14.test
│ │ │ ├── food_heuristic_15.solution
│ │ │ ├── food_heuristic_15.test
│ │ │ ├── food_heuristic_16.solution
│ │ │ ├── food_heuristic_16.test
│ │ │ ├── food_heuristic_17.solution
│ │ │ ├── food_heuristic_17.test
│ │ │ ├── food_heuristic_2.solution
│ │ │ ├── food_heuristic_2.test
│ │ │ ├── food_heuristic_3.solution
│ │ │ ├── food_heuristic_3.test
│ │ │ ├── food_heuristic_4.solution
│ │ │ ├── food_heuristic_4.test
│ │ │ ├── food_heuristic_5.solution
│ │ │ ├── food_heuristic_5.test
│ │ │ ├── food_heuristic_6.solution
│ │ │ ├── food_heuristic_6.test
│ │ │ ├── food_heuristic_7.solution
│ │ │ ├── food_heuristic_7.test
│ │ │ ├── food_heuristic_8.solution
│ │ │ ├── food_heuristic_8.test
│ │ │ ├── food_heuristic_9.solution
│ │ │ ├── food_heuristic_9.test
│ │ │ ├── food_heuristic_grade_tricky.solution
│ │ │ └── food_heuristic_grade_tricky.test
│ │ └── q8/
│ │ ├── CONFIG
│ │ ├── closest_dot_1.solution
│ │ ├── closest_dot_1.test
│ │ ├── closest_dot_10.solution
│ │ ├── closest_dot_10.test
│ │ ├── closest_dot_11.solution
│ │ ├── closest_dot_11.test
│ │ ├── closest_dot_12.solution
│ │ ├── closest_dot_12.test
│ │ ├── closest_dot_13.solution
│ │ ├── closest_dot_13.test
│ │ ├── closest_dot_2.solution
│ │ ├── closest_dot_2.test
│ │ ├── closest_dot_3.solution
│ │ ├── closest_dot_3.test
│ │ ├── closest_dot_4.solution
│ │ ├── closest_dot_4.test
│ │ ├── closest_dot_5.solution
│ │ ├── closest_dot_5.test
│ │ ├── closest_dot_6.solution
│ │ ├── closest_dot_6.test
│ │ ├── closest_dot_7.solution
│ │ ├── closest_dot_7.test
│ │ ├── closest_dot_8.solution
│ │ ├── closest_dot_8.test
│ │ ├── closest_dot_9.solution
│ │ └── closest_dot_9.test
│ ├── textDisplay.py
│ └── util.py
├── Project-2/
│ ├── VERSION
│ ├── autograder.py
│ ├── game.py
│ ├── ghostAgents.py
│ ├── grading.py
│ ├── graphicsDisplay.py
│ ├── graphicsUtils.py
│ ├── keyboardAgents.py
│ ├── layout.py
│ ├── layouts/
│ │ ├── capsuleClassic.lay
│ │ ├── contestClassic.lay
│ │ ├── mediumClassic.lay
│ │ ├── minimaxClassic.lay
│ │ ├── openClassic.lay
│ │ ├── originalClassic.lay
│ │ ├── smallClassic.lay
│ │ ├── testClassic.lay
│ │ ├── trappedClassic.lay
│ │ └── trickyClassic.lay
│ ├── multiAgents.py
│ ├── multiagentTestClasses.py
│ ├── pacman.py
│ ├── pacmanAgents.py
│ ├── projectParams.py
│ ├── testClasses.py
│ ├── testParser.py
│ ├── test_cases/
│ │ ├── CONFIG
│ │ ├── extra/
│ │ │ ├── CONFIG
│ │ │ └── grade-agent.test
│ │ ├── q1/
│ │ │ ├── CONFIG
│ │ │ ├── grade-agent.solution
│ │ │ └── grade-agent.test
│ │ ├── q2/
│ │ │ ├── 0-lecture-6-tree.solution
│ │ │ ├── 0-lecture-6-tree.test
│ │ │ ├── 0-small-tree.solution
│ │ │ ├── 0-small-tree.test
│ │ │ ├── 1-1-minmax.solution
│ │ │ ├── 1-1-minmax.test
│ │ │ ├── 1-2-minmax.solution
│ │ │ ├── 1-2-minmax.test
│ │ │ ├── 1-3-minmax.solution
│ │ │ ├── 1-3-minmax.test
│ │ │ ├── 1-4-minmax.solution
│ │ │ ├── 1-4-minmax.test
│ │ │ ├── 1-5-minmax.solution
│ │ │ ├── 1-5-minmax.test
│ │ │ ├── 1-6-minmax.solution
│ │ │ ├── 1-6-minmax.test
│ │ │ ├── 1-7-minmax.solution
│ │ │ ├── 1-7-minmax.test
│ │ │ ├── 1-8-minmax.solution
│ │ │ ├── 1-8-minmax.test
│ │ │ ├── 2-1a-vary-depth.solution
│ │ │ ├── 2-1a-vary-depth.test
│ │ │ ├── 2-1b-vary-depth.solution
│ │ │ ├── 2-1b-vary-depth.test
│ │ │ ├── 2-2a-vary-depth.solution
│ │ │ ├── 2-2a-vary-depth.test
│ │ │ ├── 2-2b-vary-depth.solution
│ │ │ ├── 2-2b-vary-depth.test
│ │ │ ├── 2-3a-vary-depth.solution
│ │ │ ├── 2-3a-vary-depth.test
│ │ │ ├── 2-3b-vary-depth.solution
│ │ │ ├── 2-3b-vary-depth.test
│ │ │ ├── 2-4a-vary-depth.solution
│ │ │ ├── 2-4a-vary-depth.test
│ │ │ ├── 2-4b-vary-depth.solution
│ │ │ ├── 2-4b-vary-depth.test
│ │ │ ├── 2-one-ghost-3level.solution
│ │ │ ├── 2-one-ghost-3level.test
│ │ │ ├── 3-one-ghost-4level.solution
│ │ │ ├── 3-one-ghost-4level.test
│ │ │ ├── 4-two-ghosts-3level.solution
│ │ │ ├── 4-two-ghosts-3level.test
│ │ │ ├── 5-two-ghosts-4level.solution
│ │ │ ├── 5-two-ghosts-4level.test
│ │ │ ├── 6-tied-root.solution
│ │ │ ├── 6-tied-root.test
│ │ │ ├── 7-1a-check-depth-one-ghost.solution
│ │ │ ├── 7-1a-check-depth-one-ghost.test
│ │ │ ├── 7-1b-check-depth-one-ghost.solution
│ │ │ ├── 7-1b-check-depth-one-ghost.test
│ │ │ ├── 7-1c-check-depth-one-ghost.solution
│ │ │ ├── 7-1c-check-depth-one-ghost.test
│ │ │ ├── 7-2a-check-depth-two-ghosts.solution
│ │ │ ├── 7-2a-check-depth-two-ghosts.test
│ │ │ ├── 7-2b-check-depth-two-ghosts.solution
│ │ │ ├── 7-2b-check-depth-two-ghosts.test
│ │ │ ├── 7-2c-check-depth-two-ghosts.solution
│ │ │ ├── 7-2c-check-depth-two-ghosts.test
│ │ │ ├── 8-pacman-game.solution
│ │ │ ├── 8-pacman-game.test
│ │ │ └── CONFIG
│ │ ├── q3/
│ │ │ ├── 0-lecture-6-tree.solution
│ │ │ ├── 0-lecture-6-tree.test
│ │ │ ├── 0-small-tree.solution
│ │ │ ├── 0-small-tree.test
│ │ │ ├── 1-1-minmax.solution
│ │ │ ├── 1-1-minmax.test
│ │ │ ├── 1-2-minmax.solution
│ │ │ ├── 1-2-minmax.test
│ │ │ ├── 1-3-minmax.solution
│ │ │ ├── 1-3-minmax.test
│ │ │ ├── 1-4-minmax.solution
│ │ │ ├── 1-4-minmax.test
│ │ │ ├── 1-5-minmax.solution
│ │ │ ├── 1-5-minmax.test
│ │ │ ├── 1-6-minmax.solution
│ │ │ ├── 1-6-minmax.test
│ │ │ ├── 1-7-minmax.solution
│ │ │ ├── 1-7-minmax.test
│ │ │ ├── 1-8-minmax.solution
│ │ │ ├── 1-8-minmax.test
│ │ │ ├── 2-1a-vary-depth.solution
│ │ │ ├── 2-1a-vary-depth.test
│ │ │ ├── 2-1b-vary-depth.solution
│ │ │ ├── 2-1b-vary-depth.test
│ │ │ ├── 2-2a-vary-depth.solution
│ │ │ ├── 2-2a-vary-depth.test
│ │ │ ├── 2-2b-vary-depth.solution
│ │ │ ├── 2-2b-vary-depth.test
│ │ │ ├── 2-3a-vary-depth.solution
│ │ │ ├── 2-3a-vary-depth.test
│ │ │ ├── 2-3b-vary-depth.solution
│ │ │ ├── 2-3b-vary-depth.test
│ │ │ ├── 2-4a-vary-depth.solution
│ │ │ ├── 2-4a-vary-depth.test
│ │ │ ├── 2-4b-vary-depth.solution
│ │ │ ├── 2-4b-vary-depth.test
│ │ │ ├── 2-one-ghost-3level.solution
│ │ │ ├── 2-one-ghost-3level.test
│ │ │ ├── 3-one-ghost-4level.solution
│ │ │ ├── 3-one-ghost-4level.test
│ │ │ ├── 4-two-ghosts-3level.solution
│ │ │ ├── 4-two-ghosts-3level.test
│ │ │ ├── 5-two-ghosts-4level.solution
│ │ │ ├── 5-two-ghosts-4level.test
│ │ │ ├── 6-tied-root.solution
│ │ │ ├── 6-tied-root.test
│ │ │ ├── 7-1a-check-depth-one-ghost.solution
│ │ │ ├── 7-1a-check-depth-one-ghost.test
│ │ │ ├── 7-1b-check-depth-one-ghost.solution
│ │ │ ├── 7-1b-check-depth-one-ghost.test
│ │ │ ├── 7-1c-check-depth-one-ghost.solution
│ │ │ ├── 7-1c-check-depth-one-ghost.test
│ │ │ ├── 7-2a-check-depth-two-ghosts.solution
│ │ │ ├── 7-2a-check-depth-two-ghosts.test
│ │ │ ├── 7-2b-check-depth-two-ghosts.solution
│ │ │ ├── 7-2b-check-depth-two-ghosts.test
│ │ │ ├── 7-2c-check-depth-two-ghosts.solution
│ │ │ ├── 7-2c-check-depth-two-ghosts.test
│ │ │ ├── 8-pacman-game.solution
│ │ │ ├── 8-pacman-game.test
│ │ │ └── CONFIG
│ │ ├── q4/
│ │ │ ├── 0-expectimax1.solution
│ │ │ ├── 0-expectimax1.test
│ │ │ ├── 1-expectimax2.solution
│ │ │ ├── 1-expectimax2.test
│ │ │ ├── 2-one-ghost-3level.solution
│ │ │ ├── 2-one-ghost-3level.test
│ │ │ ├── 3-one-ghost-4level.solution
│ │ │ ├── 3-one-ghost-4level.test
│ │ │ ├── 4-two-ghosts-3level.solution
│ │ │ ├── 4-two-ghosts-3level.test
│ │ │ ├── 5-two-ghosts-4level.solution
│ │ │ ├── 5-two-ghosts-4level.test
│ │ │ ├── 6-1a-check-depth-one-ghost.solution
│ │ │ ├── 6-1a-check-depth-one-ghost.test
│ │ │ ├── 6-1b-check-depth-one-ghost.solution
│ │ │ ├── 6-1b-check-depth-one-ghost.test
│ │ │ ├── 6-1c-check-depth-one-ghost.solution
│ │ │ ├── 6-1c-check-depth-one-ghost.test
│ │ │ ├── 6-2a-check-depth-two-ghosts.solution
│ │ │ ├── 6-2a-check-depth-two-ghosts.test
│ │ │ ├── 6-2b-check-depth-two-ghosts.solution
│ │ │ ├── 6-2b-check-depth-two-ghosts.test
│ │ │ ├── 6-2c-check-depth-two-ghosts.solution
│ │ │ ├── 6-2c-check-depth-two-ghosts.test
│ │ │ ├── 7-pacman-game.solution
│ │ │ ├── 7-pacman-game.test
│ │ │ └── CONFIG
│ │ └── q5/
│ │ ├── CONFIG
│ │ ├── grade-agent.solution
│ │ └── grade-agent.test
│ ├── textDisplay.py
│ └── util.py
├── Project-3/
│ ├── VERSION
│ ├── analysis.py
│ ├── autograder.py
│ ├── crawler.py
│ ├── environment.py
│ ├── featureExtractors.py
│ ├── game.py
│ ├── ghostAgents.py
│ ├── grading.py
│ ├── graphicsCrawlerDisplay.py
│ ├── graphicsDisplay.py
│ ├── graphicsGridworldDisplay.py
│ ├── graphicsUtils.py
│ ├── gridworld.py
│ ├── keyboardAgents.py
│ ├── layout.py
│ ├── layouts/
│ │ ├── capsuleClassic.lay
│ │ ├── contestClassic.lay
│ │ ├── mediumClassic.lay
│ │ ├── mediumGrid.lay
│ │ ├── minimaxClassic.lay
│ │ ├── openClassic.lay
│ │ ├── originalClassic.lay
│ │ ├── smallClassic.lay
│ │ ├── smallGrid.lay
│ │ ├── testClassic.lay
│ │ ├── trappedClassic.lay
│ │ └── trickyClassic.lay
│ ├── learningAgents.py
│ ├── mdp.py
│ ├── pacman.py
│ ├── pacmanAgents.py
│ ├── projectParams.py
│ ├── qlearningAgents.py
│ ├── reinforcementTestClasses.py
│ ├── testClasses.py
│ ├── testParser.py
│ ├── test_cases/
│ │ ├── CONFIG
│ │ ├── q1/
│ │ │ ├── 1-tinygrid.solution
│ │ │ ├── 1-tinygrid.test
│ │ │ ├── 2-tinygrid-noisy.solution
│ │ │ ├── 2-tinygrid-noisy.test
│ │ │ ├── 3-bridge.solution
│ │ │ ├── 3-bridge.test
│ │ │ ├── 4-discountgrid.solution
│ │ │ ├── 4-discountgrid.test
│ │ │ └── CONFIG
│ │ ├── q2/
│ │ │ ├── 1-bridge-grid.solution
│ │ │ ├── 1-bridge-grid.test
│ │ │ └── CONFIG
│ │ ├── q3/
│ │ │ ├── 1-question-3.1.solution
│ │ │ ├── 1-question-3.1.test
│ │ │ ├── 2-question-3.2.solution
│ │ │ ├── 2-question-3.2.test
│ │ │ ├── 3-question-3.3.solution
│ │ │ ├── 3-question-3.3.test
│ │ │ ├── 4-question-3.4.solution
│ │ │ ├── 4-question-3.4.test
│ │ │ ├── 5-question-3.5.solution
│ │ │ ├── 5-question-3.5.test
│ │ │ └── CONFIG
│ │ ├── q4/
│ │ │ ├── 1-tinygrid.solution
│ │ │ ├── 1-tinygrid.test
│ │ │ ├── 2-tinygrid-noisy.solution
│ │ │ ├── 2-tinygrid-noisy.test
│ │ │ ├── 3-bridge.solution
│ │ │ ├── 3-bridge.test
│ │ │ ├── 4-discountgrid.solution
│ │ │ ├── 4-discountgrid.test
│ │ │ └── CONFIG
│ │ ├── q5/
│ │ │ ├── 1-tinygrid.solution
│ │ │ ├── 1-tinygrid.test
│ │ │ ├── 2-tinygrid-noisy.solution
│ │ │ ├── 2-tinygrid-noisy.test
│ │ │ ├── 3-bridge.solution
│ │ │ ├── 3-bridge.test
│ │ │ ├── 4-discountgrid.solution
│ │ │ ├── 4-discountgrid.test
│ │ │ └── CONFIG
│ │ ├── q6/
│ │ │ ├── CONFIG
│ │ │ ├── grade-agent.solution
│ │ │ └── grade-agent.test
│ │ ├── q7/
│ │ │ ├── CONFIG
│ │ │ ├── grade-agent.solution
│ │ │ └── grade-agent.test
│ │ └── q8/
│ │ ├── 1-tinygrid.solution
│ │ ├── 1-tinygrid.test
│ │ ├── 2-tinygrid-noisy.solution
│ │ ├── 2-tinygrid-noisy.test
│ │ ├── 3-bridge.solution
│ │ ├── 3-bridge.test
│ │ ├── 4-discountgrid.solution
│ │ ├── 4-discountgrid.test
│ │ ├── 5-coord-extractor.solution
│ │ ├── 5-coord-extractor.test
│ │ └── CONFIG
│ ├── textDisplay.py
│ ├── textGridworldDisplay.py
│ ├── util.py
│ └── valueIterationAgents.py
├── Project-4/
│ ├── VERSION
│ ├── autograder.py
│ ├── busters.py
│ ├── bustersAgents.py
│ ├── bustersGhostAgents.py
│ ├── distanceCalculator.py
│ ├── game.py
│ ├── ghostAgents.py
│ ├── grading.py
│ ├── graphicsDisplay.py
│ ├── graphicsUtils.py
│ ├── inference.py
│ ├── keyboardAgents.py
│ ├── layout.py
│ ├── layouts/
│ │ ├── bigHunt.lay
│ │ ├── oneHunt.lay
│ │ ├── openHunt.lay
│ │ └── smallHunt.lay
│ ├── pacman.py
│ ├── projectParams.py
│ ├── testClasses.py
│ ├── testParser.py
│ ├── test_cases/
│ │ ├── CONFIG
│ │ ├── q1/
│ │ │ ├── 1-ExactObserve.solution
│ │ │ ├── 1-ExactObserve.test
│ │ │ ├── 2-ExactObserve.solution
│ │ │ ├── 2-ExactObserve.test
│ │ │ ├── 3-ExactObserve.solution
│ │ │ ├── 3-ExactObserve.test
│ │ │ ├── 4-ExactObserve.solution
│ │ │ ├── 4-ExactObserve.test
│ │ │ └── CONFIG
│ │ ├── q2/
│ │ │ ├── 1-ExactElapse.solution
│ │ │ ├── 1-ExactElapse.test
│ │ │ ├── 2-ExactElapse.solution
│ │ │ ├── 2-ExactElapse.test
│ │ │ ├── 3-ExactElapse.solution
│ │ │ ├── 3-ExactElapse.test
│ │ │ ├── 4-ExactElapse.solution
│ │ │ ├── 4-ExactElapse.test
│ │ │ └── CONFIG
│ │ ├── q3/
│ │ │ ├── 1-ExactObserveElapse.solution
│ │ │ ├── 1-ExactObserveElapse.test
│ │ │ ├── 2-ExactObserveElapse.solution
│ │ │ ├── 2-ExactObserveElapse.test
│ │ │ ├── 3-gameScoreTest.solution
│ │ │ ├── 3-gameScoreTest.test
│ │ │ └── CONFIG
│ │ ├── q4/
│ │ │ ├── 1-ParticleObserve.solution
│ │ │ ├── 1-ParticleObserve.test
│ │ │ ├── 2-ParticleObserve.solution
│ │ │ ├── 2-ParticleObserve.test
│ │ │ ├── 3-ParticleObserve.solution
│ │ │ ├── 3-ParticleObserve.test
│ │ │ ├── 4-ParticleObserve.solution
│ │ │ ├── 4-ParticleObserve.test
│ │ │ ├── 5-ParticleObserve.solution
│ │ │ ├── 5-ParticleObserve.test
│ │ │ ├── 6-ParticleObserve.solution
│ │ │ ├── 6-ParticleObserve.test
│ │ │ ├── 7-ParticleObserve.solution
│ │ │ ├── 7-ParticleObserve.test
│ │ │ └── CONFIG
│ │ ├── q5/
│ │ │ ├── 1-ParticleElapse.solution
│ │ │ ├── 1-ParticleElapse.test
│ │ │ ├── 2-ParticleElapse.solution
│ │ │ ├── 2-ParticleElapse.test
│ │ │ ├── 3-ParticleElapse.solution
│ │ │ ├── 3-ParticleElapse.test
│ │ │ ├── 4-ParticleElapse.solution
│ │ │ ├── 4-ParticleElapse.test
│ │ │ ├── 5-ParticleElapse.solution
│ │ │ ├── 5-ParticleElapse.test
│ │ │ ├── 6-ParticleElapse.solution
│ │ │ ├── 6-ParticleElapse.test
│ │ │ └── CONFIG
│ │ ├── q6/
│ │ │ ├── 1-JointParticleObserve.solution
│ │ │ ├── 1-JointParticleObserve.test
│ │ │ ├── 2-JointParticleObserve.solution
│ │ │ ├── 2-JointParticleObserve.test
│ │ │ ├── 3-JointParticleObserve.solution
│ │ │ ├── 3-JointParticleObserve.test
│ │ │ ├── 4-JointParticleObserve.solution
│ │ │ ├── 4-JointParticleObserve.test
│ │ │ ├── 5-JointParticleObserve.solution
│ │ │ ├── 5-JointParticleObserve.test
│ │ │ └── CONFIG
│ │ └── q7/
│ │ ├── 1-JointParticleElapse.solution
│ │ ├── 1-JointParticleElapse.test
│ │ ├── 2-JointParticleElapse.solution
│ │ ├── 2-JointParticleElapse.test
│ │ ├── 3-JointParticleObserveElapse.solution
│ │ ├── 3-JointParticleObserveElapse.test
│ │ └── CONFIG
│ ├── textDisplay.py
│ ├── trackingTestClasses.py
│ └── util.py
├── Project-5/
│ ├── VERSION
│ ├── answers.py
│ ├── autograder.py
│ ├── classificationAgents.py
│ ├── classificationMethod.py
│ ├── classificationTestClasses.py
│ ├── data/
│ │ ├── digitdata/
│ │ │ ├── testimages
│ │ │ ├── testlabels
│ │ │ ├── trainingimages
│ │ │ ├── traininglabels
│ │ │ ├── validationimages
│ │ │ └── validationlabels
│ │ ├── facedata/
│ │ │ ├── facedatatest
│ │ │ ├── facedatatestlabels
│ │ │ ├── facedatatrain
│ │ │ ├── facedatatrainlabels
│ │ │ ├── facedatavalidation
│ │ │ └── facedatavalidationlabels
│ │ └── pacmandata/
│ │ ├── contest_test.pkl
│ │ ├── contest_training.pkl
│ │ ├── contest_validation.pkl
│ │ ├── food_test.pkl
│ │ ├── food_training.pkl
│ │ ├── food_validation.pkl
│ │ ├── stop_test.pkl
│ │ ├── stop_training.pkl
│ │ ├── stop_validation.pkl
│ │ ├── suicide_test.pkl
│ │ ├── suicide_training.pkl
│ │ └── suicide_validation.pkl
│ ├── dataClassifier.py
│ ├── game.py
│ ├── ghostAgents.py
│ ├── grading.py
│ ├── graphicsDisplay.py
│ ├── graphicsUtils.py
│ ├── images/
│ │ └── img2
│ ├── keyboardAgents.py
│ ├── layout.py
│ ├── layouts/
│ │ ├── capsuleClassic.lay
│ │ ├── contestClassic.lay
│ │ ├── mediumClassic.lay
│ │ ├── minimaxClassic.lay
│ │ ├── openClassic.lay
│ │ ├── originalClassic.lay
│ │ ├── smallClassic.lay
│ │ ├── testClassic.lay
│ │ ├── trappedClassic.lay
│ │ └── trickyClassic.lay
│ ├── mira.py
│ ├── mostFrequent.py
│ ├── naiveBayes.py
│ ├── pacman.py
│ ├── pacmanAgents.py
│ ├── pacmandata/
│ │ ├── contest_test.pkl
│ │ ├── contest_training.pkl
│ │ ├── contest_validation.pkl
│ │ ├── food_test.pkl
│ │ ├── food_training.pkl
│ │ ├── food_validation.pkl
│ │ ├── stop_test.pkl
│ │ ├── stop_training.pkl
│ │ ├── stop_validation.pkl
│ │ ├── suicide_test.pkl
│ │ ├── suicide_training.pkl
│ │ └── suicide_validation.pkl
│ ├── perceptron.py
│ ├── perceptron_pacman.py
│ ├── projectParams.py
│ ├── samples.py
│ ├── testClasses.py
│ ├── testParser.py
│ ├── test_cases/
│ │ ├── CONFIG
│ │ ├── q1/
│ │ │ ├── CONFIG
│ │ │ ├── grade.solution
│ │ │ └── grade.test
│ │ ├── q2/
│ │ │ ├── CONFIG
│ │ │ ├── grade.solution
│ │ │ └── grade.test
│ │ ├── q3/
│ │ │ ├── CONFIG
│ │ │ ├── grade.solution
│ │ │ └── grade.test
│ │ ├── q4/
│ │ │ ├── CONFIG
│ │ │ ├── grade.solution
│ │ │ └── grade.test
│ │ ├── q5/
│ │ │ ├── CONFIG
│ │ │ ├── contest.solution
│ │ │ ├── contest.test
│ │ │ ├── suicide.solution
│ │ │ └── suicide.test
│ │ └── q6/
│ │ ├── CONFIG
│ │ ├── contest.solution
│ │ ├── contest.test
│ │ ├── suicide.solution
│ │ └── suicide.test
│ ├── textDisplay.py
│ └── util.py
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: Project-1/VERSION
================================================
v1.001
================================================
FILE: Project-1/autograder.py
================================================
# autograder.py
# -------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
# imports from python standard library
import grading
import imp
import optparse
import os
import re
import sys
import projectParams
import random
random.seed(0)
try:
from pacman import GameState
except:
pass
# register arguments and set default values
def readCommand(argv):
parser = optparse.OptionParser(description = 'Run public tests on student code')
parser.set_defaults(generateSolutions=False, edxOutput=False, muteOutput=False, printTestCase=False, noGraphics=False)
parser.add_option('--test-directory',
dest = 'testRoot',
default = 'test_cases',
help = 'Root test directory which contains subdirectories corresponding to each question')
parser.add_option('--student-code',
dest = 'studentCode',
default = projectParams.STUDENT_CODE_DEFAULT,
help = 'comma separated list of student code files')
parser.add_option('--code-directory',
dest = 'codeRoot',
default = "",
help = 'Root directory containing the student and testClass code')
parser.add_option('--test-case-code',
dest = 'testCaseCode',
default = projectParams.PROJECT_TEST_CLASSES,
help = 'class containing testClass classes for this project')
parser.add_option('--generate-solutions',
dest = 'generateSolutions',
action = 'store_true',
help = 'Write solutions generated to .solution file')
parser.add_option('--edx-output',
dest = 'edxOutput',
action = 'store_true',
help = 'Generate edX output files')
parser.add_option('--mute',
dest = 'muteOutput',
action = 'store_true',
help = 'Mute output from executing tests')
parser.add_option('--print-tests', '-p',
dest = 'printTestCase',
action = 'store_true',
help = 'Print each test case before running them.')
parser.add_option('--test', '-t',
dest = 'runTest',
default = None,
help = 'Run one particular test. Relative to test root.')
parser.add_option('--question', '-q',
dest = 'gradeQuestion',
default = None,
help = 'Grade one particular question.')
parser.add_option('--no-graphics',
dest = 'noGraphics',
action = 'store_true',
help = 'No graphics display for pacman games.')
(options, args) = parser.parse_args(argv)
return options
# confirm we should author solution files
def confirmGenerate():
print 'WARNING: this action will overwrite any solution files.'
print 'Are you sure you want to proceed? (yes/no)'
while True:
ans = sys.stdin.readline().strip()
if ans == 'yes':
break
elif ans == 'no':
sys.exit(0)
else:
print 'please answer either "yes" or "no"'
# TODO: Fix this so that it tracebacks work correctly
# Looking at source of the traceback module, presuming it works
# the same as the intepreters, it uses co_filename. This is,
# however, a readonly attribute.
def setModuleName(module, filename):
functionType = type(confirmGenerate)
classType = type(optparse.Option)
for i in dir(module):
o = getattr(module, i)
if hasattr(o, '__file__'): continue
if type(o) == functionType:
setattr(o, '__file__', filename)
elif type(o) == classType:
setattr(o, '__file__', filename)
# TODO: assign member __file__'s?
#print i, type(o)
#from cStringIO import StringIO
def loadModuleString(moduleSource):
# Below broken, imp doesn't believe its being passed a file:
# ValueError: load_module arg#2 should be a file or None
#
#f = StringIO(moduleCodeDict[k])
#tmp = imp.load_module(k, f, k, (".py", "r", imp.PY_SOURCE))
tmp = imp.new_module(k)
exec moduleCodeDict[k] in tmp.__dict__
setModuleName(tmp, k)
return tmp
import py_compile
def loadModuleFile(moduleName, filePath):
with open(filePath, 'r') as f:
return imp.load_module(moduleName, f, "%s.py" % moduleName, (".py", "r", imp.PY_SOURCE))
def readFile(path, root=""):
"Read file from disk at specified path and return as string"
with open(os.path.join(root, path), 'r') as handle:
return handle.read()
#######################################################################
# Error Hint Map
#######################################################################
# TODO: use these
ERROR_HINT_MAP = {
'q1': {
"<type 'exceptions.IndexError'>": """
We noticed that your project threw an IndexError on q1.
While many things may cause this, it may have been from
assuming a certain number of successors from a state space
or assuming a certain number of actions available from a given
state. Try making your code more general (no hardcoded indices)
and submit again!
"""
},
'q3': {
"<type 'exceptions.AttributeError'>": """
We noticed that your project threw an AttributeError on q3.
While many things may cause this, it may have been from assuming
a certain size or structure to the state space. For example, if you have
a line of code assuming that the state is (x, y) and we run your code
on a state space with (x, y, z), this error could be thrown. Try
making your code more general and submit again!
"""
}
}
import pprint
def splitStrings(d):
d2 = dict(d)
for k in d:
if k[0:2] == "__":
del d2[k]
continue
if d2[k].find("\n") >= 0:
d2[k] = d2[k].split("\n")
return d2
def printTest(testDict, solutionDict):
pp = pprint.PrettyPrinter(indent=4)
print "Test case:"
for line in testDict["__raw_lines__"]:
print " |", line
print "Solution:"
for line in solutionDict["__raw_lines__"]:
print " |", line
def runTest(testName, moduleDict, printTestCase=False, display=None):
import testParser
import testClasses
for module in moduleDict:
setattr(sys.modules[__name__], module, moduleDict[module])
testDict = testParser.TestParser(testName + ".test").parse()
solutionDict = testParser.TestParser(testName + ".solution").parse()
test_out_file = os.path.join('%s.test_output' % testName)
testDict['test_out_file'] = test_out_file
testClass = getattr(projectTestClasses, testDict['class'])
questionClass = getattr(testClasses, 'Question')
question = questionClass({'max_points': 0}, display)
testCase = testClass(question, testDict)
if printTestCase:
printTest(testDict, solutionDict)
# This is a fragile hack to create a stub grades object
grades = grading.Grades(projectParams.PROJECT_NAME, [(None,0)])
testCase.execute(grades, moduleDict, solutionDict)
# returns all the tests you need to run in order to run question
def getDepends(testParser, testRoot, question):
allDeps = [question]
questionDict = testParser.TestParser(os.path.join(testRoot, question, 'CONFIG')).parse()
if 'depends' in questionDict:
depends = questionDict['depends'].split()
for d in depends:
# run dependencies first
allDeps = getDepends(testParser, testRoot, d) + allDeps
return allDeps
# get list of questions to grade
def getTestSubdirs(testParser, testRoot, questionToGrade):
problemDict = testParser.TestParser(os.path.join(testRoot, 'CONFIG')).parse()
if questionToGrade != None:
questions = getDepends(testParser, testRoot, questionToGrade)
if len(questions) > 1:
print 'Note: due to dependencies, the following tests will be run: %s' % ' '.join(questions)
return questions
if 'order' in problemDict:
return problemDict['order'].split()
return sorted(os.listdir(testRoot))
# evaluate student code
def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR_HINT_MAP, edxOutput=False, muteOutput=False,
printTestCase=False, questionToGrade=None, display=None):
# imports of testbench code. note that the testClasses import must follow
# the import of student code due to dependencies
import testParser
import testClasses
for module in moduleDict:
setattr(sys.modules[__name__], module, moduleDict[module])
questions = []
questionDicts = {}
test_subdirs = getTestSubdirs(testParser, testRoot, questionToGrade)
for q in test_subdirs:
subdir_path = os.path.join(testRoot, q)
if not os.path.isdir(subdir_path) or q[0] == '.':
continue
# create a question object
questionDict = testParser.TestParser(os.path.join(subdir_path, 'CONFIG')).parse()
questionClass = getattr(testClasses, questionDict['class'])
question = questionClass(questionDict, display)
questionDicts[q] = questionDict
# load test cases into question
tests = filter(lambda t: re.match('[^#~.].*\.test\Z', t), os.listdir(subdir_path))
tests = map(lambda t: re.match('(.*)\.test\Z', t).group(1), tests)
for t in sorted(tests):
test_file = os.path.join(subdir_path, '%s.test' % t)
solution_file = os.path.join(subdir_path, '%s.solution' % t)
test_out_file = os.path.join(subdir_path, '%s.test_output' % t)
testDict = testParser.TestParser(test_file).parse()
if testDict.get("disabled", "false").lower() == "true":
continue
testDict['test_out_file'] = test_out_file
testClass = getattr(projectTestClasses, testDict['class'])
testCase = testClass(question, testDict)
def makefun(testCase, solution_file):
if generateSolutions:
# write solution file to disk
return lambda grades: testCase.writeSolution(moduleDict, solution_file)
else:
# read in solution dictionary and pass as an argument
testDict = testParser.TestParser(test_file).parse()
solutionDict = testParser.TestParser(solution_file).parse()
if printTestCase:
return lambda grades: printTest(testDict, solutionDict) or testCase.execute(grades, moduleDict, solutionDict)
else:
return lambda grades: testCase.execute(grades, moduleDict, solutionDict)
question.addTestCase(testCase, makefun(testCase, solution_file))
# Note extra function is necessary for scoping reasons
def makefun(question):
return lambda grades: question.execute(grades)
setattr(sys.modules[__name__], q, makefun(question))
questions.append((q, question.getMaxPoints()))
grades = grading.Grades(projectParams.PROJECT_NAME, questions, edxOutput=edxOutput, muteOutput=muteOutput)
if questionToGrade == None:
for q in questionDicts:
for prereq in questionDicts[q].get('depends', '').split():
grades.addPrereq(q, prereq)
grades.grade(sys.modules[__name__], bonusPic = projectParams.BONUS_PIC)
return grades.points
def getDisplay(graphicsByDefault, options=None):
graphics = graphicsByDefault
if options is not None and options.noGraphics:
graphics = False
if graphics:
try:
import graphicsDisplay
return graphicsDisplay.PacmanGraphics(1, frameTime=.05)
except ImportError:
pass
import textDisplay
return textDisplay.NullGraphics()
if __name__ == '__main__':
options = readCommand(sys.argv)
if options.generateSolutions:
confirmGenerate()
codePaths = options.studentCode.split(',')
# moduleCodeDict = {}
# for cp in codePaths:
# moduleName = re.match('.*?([^/]*)\.py', cp).group(1)
# moduleCodeDict[moduleName] = readFile(cp, root=options.codeRoot)
# moduleCodeDict['projectTestClasses'] = readFile(options.testCaseCode, root=options.codeRoot)
# moduleDict = loadModuleDict(moduleCodeDict)
moduleDict = {}
for cp in codePaths:
moduleName = re.match('.*?([^/]*)\.py', cp).group(1)
moduleDict[moduleName] = loadModuleFile(moduleName, os.path.join(options.codeRoot, cp))
moduleName = re.match('.*?([^/]*)\.py', options.testCaseCode).group(1)
moduleDict['projectTestClasses'] = loadModuleFile(moduleName, os.path.join(options.codeRoot, options.testCaseCode))
if options.runTest != None:
runTest(options.runTest, moduleDict, printTestCase=options.printTestCase, display=getDisplay(True, options))
else:
evaluate(options.generateSolutions, options.testRoot, moduleDict,
edxOutput=options.edxOutput, muteOutput=options.muteOutput, printTestCase=options.printTestCase,
questionToGrade=options.gradeQuestion, display=getDisplay(options.gradeQuestion!=None, options))
================================================
FILE: Project-1/commands.txt
================================================
python pacman.py
python pacman.py --layout testMaze --pacman GoWestAgent
python pacman.py --layout tinyMaze --pacman GoWestAgent
python pacman.py -h
python pacman.py -l tinyMaze -p SearchAgent -a fn=tinyMazeSearch
python pacman.py -l tinyMaze -p SearchAgent
python pacman.py -l mediumMaze -p SearchAgent
python pacman.py -l bigMaze -z .5 -p SearchAgent
python pacman.py -l mediumMaze -p SearchAgent -a fn=bfs
python pacman.py -l bigMaze -p SearchAgent -a fn=bfs -z .5
python eightpuzzle.py
python pacman.py -l mediumMaze -p SearchAgent -a fn=ucs
python pacman.py -l mediumDottedMaze -p StayEastSearchAgent
python pacman.py -l mediumScaryMaze -p StayWestSearchAgent
python pacman.py -l bigMaze -z .5 -p SearchAgent -a fn=astar,heuristic=manhattanHeuristic
python pacman.py -l tinyCorners -p SearchAgent -a fn=bfs,prob=CornersProblem
python pacman.py -l mediumCorners -p SearchAgent -a fn=bfs,prob=CornersProblem
python pacman.py -l mediumCorners -p AStarCornersAgent -z 0.5
python pacman.py -l testSearch -p AStarFoodSearchAgent
python pacman.py -l trickySearch -p AStarFoodSearchAgent
python pacman.py -l bigSearch -p ClosestDotSearchAgent -z .5
python pacman.py -l bigSearch -p ApproximateSearchAgent -z .5 -q
================================================
FILE: Project-1/eightpuzzle.py
================================================
# eightpuzzle.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
import search
import random
# Module Classes
class EightPuzzleState:
"""
The Eight Puzzle is described in the course textbook on
page 64.
This class defines the mechanics of the puzzle itself. The
task of recasting this puzzle as a search problem is left to
the EightPuzzleSearchProblem class.
"""
def __init__( self, numbers ):
"""
Constructs a new eight puzzle from an ordering of numbers.
numbers: a list of integers from 0 to 8 representing an
instance of the eight puzzle. 0 represents the blank
space. Thus, the list
[1, 0, 2, 3, 4, 5, 6, 7, 8]
represents the eight puzzle:
-------------
| 1 | | 2 |
-------------
| 3 | 4 | 5 |
-------------
| 6 | 7 | 8 |
------------
The configuration of the puzzle is stored in a 2-dimensional
list (a list of lists) 'cells'.
"""
self.cells = []
numbers = numbers[:] # Make a copy so as not to cause side-effects.
numbers.reverse()
for row in range( 3 ):
self.cells.append( [] )
for col in range( 3 ):
self.cells[row].append( numbers.pop() )
if self.cells[row][col] == 0:
self.blankLocation = row, col
def isGoal( self ):
"""
Checks to see if the puzzle is in its goal state.
-------------
| | 1 | 2 |
-------------
| 3 | 4 | 5 |
-------------
| 6 | 7 | 8 |
-------------
>>> EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]).isGoal()
True
>>> EightPuzzleState([1, 0, 2, 3, 4, 5, 6, 7, 8]).isGoal()
False
"""
current = 0
for row in range( 3 ):
for col in range( 3 ):
if current != self.cells[row][col]:
return False
current += 1
return True
def legalMoves( self ):
"""
Returns a list of legal moves from the current state.
Moves consist of moving the blank space up, down, left or right.
These are encoded as 'up', 'down', 'left' and 'right' respectively.
>>> EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]).legalMoves()
['down', 'right']
"""
moves = []
row, col = self.blankLocation
if(row != 0):
moves.append('up')
if(row != 2):
moves.append('down')
if(col != 0):
moves.append('left')
if(col != 2):
moves.append('right')
return moves
def result(self, move):
"""
Returns a new eightPuzzle with the current state and blankLocation
updated based on the provided move.
The move should be a string drawn from a list returned by legalMoves.
Illegal moves will raise an exception, which may be an array bounds
exception.
NOTE: This function *does not* change the current object. Instead,
it returns a new object.
"""
row, col = self.blankLocation
if(move == 'up'):
newrow = row - 1
newcol = col
elif(move == 'down'):
newrow = row + 1
newcol = col
elif(move == 'left'):
newrow = row
newcol = col - 1
elif(move == 'right'):
newrow = row
newcol = col + 1
else:
raise "Illegal Move"
# Create a copy of the current eightPuzzle
newPuzzle = EightPuzzleState([0, 0, 0, 0, 0, 0, 0, 0, 0])
newPuzzle.cells = [values[:] for values in self.cells]
# And update it to reflect the move
newPuzzle.cells[row][col] = self.cells[newrow][newcol]
newPuzzle.cells[newrow][newcol] = self.cells[row][col]
newPuzzle.blankLocation = newrow, newcol
return newPuzzle
# Utilities for comparison and display
def __eq__(self, other):
"""
Overloads '==' such that two eightPuzzles with the same configuration
are equal.
>>> EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]) == \
EightPuzzleState([1, 0, 2, 3, 4, 5, 6, 7, 8]).result('left')
True
"""
for row in range( 3 ):
if self.cells[row] != other.cells[row]:
return False
return True
def __hash__(self):
return hash(str(self.cells))
def __getAsciiString(self):
"""
Returns a display string for the maze
"""
lines = []
horizontalLine = ('-' * (13))
lines.append(horizontalLine)
for row in self.cells:
rowLine = '|'
for col in row:
if col == 0:
col = ' '
rowLine = rowLine + ' ' + col.__str__() + ' |'
lines.append(rowLine)
lines.append(horizontalLine)
return '\n'.join(lines)
def __str__(self):
return self.__getAsciiString()
# TODO: Implement The methods in this class
class EightPuzzleSearchProblem(search.SearchProblem):
"""
Implementation of a SearchProblem for the Eight Puzzle domain
Each state is represented by an instance of an eightPuzzle.
"""
def __init__(self,puzzle):
"Creates a new EightPuzzleSearchProblem which stores search information."
self.puzzle = puzzle
def getStartState(self):
return puzzle
def isGoalState(self,state):
return state.isGoal()
def getSuccessors(self,state):
"""
Returns list of (successor, action, stepCost) pairs where
each succesor is either left, right, up, or down
from the original state and the cost is 1.0 for each
"""
succ = []
for a in state.legalMoves():
succ.append((state.result(a), a, 1))
return succ
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions. The sequence must
be composed of legal moves
"""
return len(actions)
EIGHT_PUZZLE_DATA = [[1, 0, 2, 3, 4, 5, 6, 7, 8],
[1, 7, 8, 2, 3, 4, 5, 6, 0],
[4, 3, 2, 7, 0, 5, 1, 6, 8],
[5, 1, 3, 4, 0, 2, 6, 7, 8],
[1, 2, 5, 7, 6, 8, 0, 4, 3],
[0, 3, 1, 6, 8, 2, 7, 5, 4]]
def loadEightPuzzle(puzzleNumber):
"""
puzzleNumber: The number of the eight puzzle to load.
Returns an eight puzzle object generated from one of the
provided puzzles in EIGHT_PUZZLE_DATA.
puzzleNumber can range from 0 to 5.
>>> print loadEightPuzzle(0)
-------------
| 1 | | 2 |
-------------
| 3 | 4 | 5 |
-------------
| 6 | 7 | 8 |
-------------
"""
return EightPuzzleState(EIGHT_PUZZLE_DATA[puzzleNumber])
def createRandomEightPuzzle(moves=100):
"""
moves: number of random moves to apply
Creates a random eight puzzle by applying
a series of 'moves' random moves to a solved
puzzle.
"""
puzzle = EightPuzzleState([0,1,2,3,4,5,6,7,8])
for i in range(moves):
# Execute a random legal move
puzzle = puzzle.result(random.sample(puzzle.legalMoves(), 1)[0])
return puzzle
if __name__ == '__main__':
puzzle = createRandomEightPuzzle(25)
print('A random puzzle:')
print(puzzle)
problem = EightPuzzleSearchProblem(puzzle)
path = search.breadthFirstSearch(problem)
print('BFS found a path of %d moves: %s' % (len(path), str(path)))
curr = puzzle
i = 1
for a in path:
curr = curr.result(a)
print('After %d move%s: %s' % (i, ("", "s")[i>1], a))
print(curr)
raw_input("Press return for the next state...") # wait for key stroke
i += 1
================================================
FILE: Project-1/game.py
================================================
# game.py
# -------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
# game.py
# -------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
from util import *
import time, os
import traceback
import sys
#######################
# Parts worth reading #
#######################
class Agent:
"""
An agent must define a getAction method, but may also define the
following methods which will be called if they exist:
def registerInitialState(self, state): # inspects the starting state
"""
def __init__(self, index=0):
self.index = index
def getAction(self, state):
"""
The Agent will receive a GameState (from either {pacman, capture, sonar}.py) and
must return an action from Directions.{North, South, East, West, Stop}
"""
raiseNotDefined()
class Directions:
NORTH = 'North'
SOUTH = 'South'
EAST = 'East'
WEST = 'West'
STOP = 'Stop'
LEFT = {NORTH: WEST,
SOUTH: EAST,
EAST: NORTH,
WEST: SOUTH,
STOP: STOP}
RIGHT = dict([(y,x) for x, y in LEFT.items()])
REVERSE = {NORTH: SOUTH,
SOUTH: NORTH,
EAST: WEST,
WEST: EAST,
STOP: STOP}
class Configuration:
"""
A Configuration holds the (x,y) coordinate of a character, along with its
traveling direction.
The convention for positions, like a graph, is that (0,0) is the lower left corner, x increases
horizontally and y increases vertically. Therefore, north is the direction of increasing y, or (0,1).
"""
def __init__(self, pos, direction):
self.pos = pos
self.direction = direction
def getPosition(self):
return (self.pos)
def getDirection(self):
return self.direction
def isInteger(self):
x,y = self.pos
return x == int(x) and y == int(y)
def __eq__(self, other):
if other == None: return False
return (self.pos == other.pos and self.direction == other.direction)
def __hash__(self):
x = hash(self.pos)
y = hash(self.direction)
return hash(x + 13 * y)
def __str__(self):
return "(x,y)="+str(self.pos)+", "+str(self.direction)
def generateSuccessor(self, vector):
"""
Generates a new configuration reached by translating the current
configuration by the action vector. This is a low-level call and does
not attempt to respect the legality of the movement.
Actions are movement vectors.
"""
x, y= self.pos
dx, dy = vector
direction = Actions.vectorToDirection(vector)
if direction == Directions.STOP:
direction = self.direction # There is no stop direction
return Configuration((x + dx, y+dy), direction)
class AgentState:
"""
AgentStates hold the state of an agent (configuration, speed, scared, etc).
"""
def __init__( self, startConfiguration, isPacman ):
self.start = startConfiguration
self.configuration = startConfiguration
self.isPacman = isPacman
self.scaredTimer = 0
self.numCarrying = 0
self.numReturned = 0
def __str__( self ):
if self.isPacman:
return "Pacman: " + str( self.configuration )
else:
return "Ghost: " + str( self.configuration )
def __eq__( self, other ):
if other == None:
return False
return self.configuration == other.configuration and self.scaredTimer == other.scaredTimer
def __hash__(self):
return hash(hash(self.configuration) + 13 * hash(self.scaredTimer))
def copy( self ):
state = AgentState( self.start, self.isPacman )
state.configuration = self.configuration
state.scaredTimer = self.scaredTimer
state.numCarrying = self.numCarrying
state.numReturned = self.numReturned
return state
def getPosition(self):
if self.configuration == None: return None
return self.configuration.getPosition()
def getDirection(self):
return self.configuration.getDirection()
class Grid:
"""
A 2-dimensional array of objects backed by a list of lists. Data is accessed
via grid[x][y] where (x,y) are positions on a Pacman map with x horizontal,
y vertical and the origin (0,0) in the bottom left corner.
The __str__ method constructs an output that is oriented like a pacman board.
"""
def __init__(self, width, height, initialValue=False, bitRepresentation=None):
if initialValue not in [False, True]: raise Exception('Grids can only contain booleans')
self.CELLS_PER_INT = 30
self.width = width
self.height = height
self.data = [[initialValue for y in range(height)] for x in range(width)]
if bitRepresentation:
self._unpackBits(bitRepresentation)
def __getitem__(self, i):
return self.data[i]
def __setitem__(self, key, item):
self.data[key] = item
def __str__(self):
out = [[str(self.data[x][y])[0] for x in range(self.width)] for y in range(self.height)]
out.reverse()
return '\n'.join([''.join(x) for x in out])
def __eq__(self, other):
if other == None: return False
return self.data == other.data
def __hash__(self):
# return hash(str(self))
base = 1
h = 0
for l in self.data:
for i in l:
if i:
h += base
base *= 2
return hash(h)
def copy(self):
g = Grid(self.width, self.height)
g.data = [x[:] for x in self.data]
return g
def deepCopy(self):
return self.copy()
def shallowCopy(self):
g = Grid(self.width, self.height)
g.data = self.data
return g
def count(self, item =True ):
return sum([x.count(item) for x in self.data])
def asList(self, key = True):
list = []
for x in range(self.width):
for y in range(self.height):
if self[x][y] == key: list.append( (x,y) )
return list
def packBits(self):
"""
Returns an efficient int list representation
(width, height, bitPackedInts...)
"""
bits = [self.width, self.height]
currentInt = 0
for i in range(self.height * self.width):
bit = self.CELLS_PER_INT - (i % self.CELLS_PER_INT) - 1
x, y = self._cellIndexToPosition(i)
if self[x][y]:
currentInt += 2 ** bit
if (i + 1) % self.CELLS_PER_INT == 0:
bits.append(currentInt)
currentInt = 0
bits.append(currentInt)
return tuple(bits)
def _cellIndexToPosition(self, index):
x = index / self.height
y = index % self.height
return x, y
def _unpackBits(self, bits):
"""
Fills in data from a bit-level representation
"""
cell = 0
for packed in bits:
for bit in self._unpackInt(packed, self.CELLS_PER_INT):
if cell == self.width * self.height: break
x, y = self._cellIndexToPosition(cell)
self[x][y] = bit
cell += 1
def _unpackInt(self, packed, size):
bools = []
if packed < 0: raise ValueError, "must be a positive integer"
for i in range(size):
n = 2 ** (self.CELLS_PER_INT - i - 1)
if packed >= n:
bools.append(True)
packed -= n
else:
bools.append(False)
return bools
def reconstituteGrid(bitRep):
if type(bitRep) is not type((1,2)):
return bitRep
width, height = bitRep[:2]
return Grid(width, height, bitRepresentation= bitRep[2:])
####################################
# Parts you shouldn't have to read #
####################################
class Actions:
"""
A collection of static methods for manipulating move actions.
"""
# Directions
_directions = {Directions.NORTH: (0, 1),
Directions.SOUTH: (0, -1),
Directions.EAST: (1, 0),
Directions.WEST: (-1, 0),
Directions.STOP: (0, 0)}
_directionsAsList = _directions.items()
TOLERANCE = .001
def reverseDirection(action):
if action == Directions.NORTH:
return Directions.SOUTH
if action == Directions.SOUTH:
return Directions.NORTH
if action == Directions.EAST:
return Directions.WEST
if action == Directions.WEST:
return Directions.EAST
return action
reverseDirection = staticmethod(reverseDirection)
def vectorToDirection(vector):
dx, dy = vector
if dy > 0:
return Directions.NORTH
if dy < 0:
return Directions.SOUTH
if dx < 0:
return Directions.WEST
if dx > 0:
return Directions.EAST
return Directions.STOP
vectorToDirection = staticmethod(vectorToDirection)
def directionToVector(direction, speed = 1.0):
dx, dy = Actions._directions[direction]
return (dx * speed, dy * speed)
directionToVector = staticmethod(directionToVector)
def getPossibleActions(config, walls):
possible = []
x, y = config.pos
x_int, y_int = int(x + 0.5), int(y + 0.5)
# In between grid points, all agents must continue straight
if (abs(x - x_int) + abs(y - y_int) > Actions.TOLERANCE):
return [config.getDirection()]
for dir, vec in Actions._directionsAsList:
dx, dy = vec
next_y = y_int + dy
next_x = x_int + dx
if not walls[next_x][next_y]: possible.append(dir)
return possible
getPossibleActions = staticmethod(getPossibleActions)
def getLegalNeighbors(position, walls):
x,y = position
x_int, y_int = int(x + 0.5), int(y + 0.5)
neighbors = []
for dir, vec in Actions._directionsAsList:
dx, dy = vec
next_x = x_int + dx
if next_x < 0 or next_x == walls.width: continue
next_y = y_int + dy
if next_y < 0 or next_y == walls.height: continue
if not walls[next_x][next_y]: neighbors.append((next_x, next_y))
return neighbors
getLegalNeighbors = staticmethod(getLegalNeighbors)
def getSuccessor(position, action):
dx, dy = Actions.directionToVector(action)
x, y = position
return (x + dx, y + dy)
getSuccessor = staticmethod(getSuccessor)
class GameStateData:
"""
"""
def __init__( self, prevState = None ):
"""
Generates a new data packet by copying information from its predecessor.
"""
if prevState != None:
self.food = prevState.food.shallowCopy()
self.capsules = prevState.capsules[:]
self.agentStates = self.copyAgentStates( prevState.agentStates )
self.layout = prevState.layout
self._eaten = prevState._eaten
self.score = prevState.score
self._foodEaten = None
self._foodAdded = None
self._capsuleEaten = None
self._agentMoved = None
self._lose = False
self._win = False
self.scoreChange = 0
def deepCopy( self ):
state = GameStateData( self )
state.food = self.food.deepCopy()
state.layout = self.layout.deepCopy()
state._agentMoved = self._agentMoved
state._foodEaten = self._foodEaten
state._foodAdded = self._foodAdded
state._capsuleEaten = self._capsuleEaten
return state
def copyAgentStates( self, agentStates ):
copiedStates = []
for agentState in agentStates:
copiedStates.append( agentState.copy() )
return copiedStates
def __eq__( self, other ):
"""
Allows two states to be compared.
"""
if other == None: return False
# TODO Check for type of other
if not self.agentStates == other.agentStates: return False
if not self.food == other.food: return False
if not self.capsules == other.capsules: return False
if not self.score == other.score: return False
return True
def __hash__( self ):
"""
Allows states to be keys of dictionaries.
"""
for i, state in enumerate( self.agentStates ):
try:
int(hash(state))
except TypeError, e:
print e
#hash(state)
return int((hash(tuple(self.agentStates)) + 13*hash(self.food) + 113* hash(tuple(self.capsules)) + 7 * hash(self.score)) % 1048575 )
def __str__( self ):
width, height = self.layout.width, self.layout.height
map = Grid(width, height)
if type(self.food) == type((1,2)):
self.food = reconstituteGrid(self.food)
for x in range(width):
for y in range(height):
food, walls = self.food, self.layout.walls
map[x][y] = self._foodWallStr(food[x][y], walls[x][y])
for agentState in self.agentStates:
if agentState == None: continue
if agentState.configuration == None: continue
x,y = [int( i ) for i in nearestPoint( agentState.configuration.pos )]
agent_dir = agentState.configuration.direction
if agentState.isPacman:
map[x][y] = self._pacStr( agent_dir )
else:
map[x][y] = self._ghostStr( agent_dir )
for x, y in self.capsules:
map[x][y] = 'o'
return str(map) + ("\nScore: %d\n" % self.score)
def _foodWallStr( self, hasFood, hasWall ):
if hasFood:
return '.'
elif hasWall:
return '%'
else:
return ' '
def _pacStr( self, dir ):
if dir == Directions.NORTH:
return 'v'
if dir == Directions.SOUTH:
return '^'
if dir == Directions.WEST:
return '>'
return '<'
def _ghostStr( self, dir ):
return 'G'
if dir == Directions.NORTH:
return 'M'
if dir == Directions.SOUTH:
return 'W'
if dir == Directions.WEST:
return '3'
return 'E'
def initialize( self, layout, numGhostAgents ):
"""
Creates an initial game state from a layout array (see layout.py).
"""
self.food = layout.food.copy()
#self.capsules = []
self.capsules = layout.capsules[:]
self.layout = layout
self.score = 0
self.scoreChange = 0
self.agentStates = []
numGhosts = 0
for isPacman, pos in layout.agentPositions:
if not isPacman:
if numGhosts == numGhostAgents: continue # Max ghosts reached already
else: numGhosts += 1
self.agentStates.append( AgentState( Configuration( pos, Directions.STOP), isPacman) )
self._eaten = [False for a in self.agentStates]
try:
import boinc
_BOINC_ENABLED = True
except:
_BOINC_ENABLED = False
class Game:
"""
The Game manages the control flow, soliciting actions from agents.
"""
def __init__( self, agents, display, rules, startingIndex=0, muteAgents=False, catchExceptions=False ):
self.agentCrashed = False
self.agents = agents
self.display = display
self.rules = rules
self.startingIndex = startingIndex
self.gameOver = False
self.muteAgents = muteAgents
self.catchExceptions = catchExceptions
self.moveHistory = []
self.totalAgentTimes = [0 for agent in agents]
self.totalAgentTimeWarnings = [0 for agent in agents]
self.agentTimeout = False
import cStringIO
self.agentOutput = [cStringIO.StringIO() for agent in agents]
def getProgress(self):
if self.gameOver:
return 1.0
else:
return self.rules.getProgress(self)
def _agentCrash( self, agentIndex, quiet=False):
"Helper method for handling agent crashes"
if not quiet: traceback.print_exc()
self.gameOver = True
self.agentCrashed = True
self.rules.agentCrash(self, agentIndex)
OLD_STDOUT = None
OLD_STDERR = None
def mute(self, agentIndex):
if not self.muteAgents: return
global OLD_STDOUT, OLD_STDERR
import cStringIO
OLD_STDOUT = sys.stdout
OLD_STDERR = sys.stderr
sys.stdout = self.agentOutput[agentIndex]
sys.stderr = self.agentOutput[agentIndex]
def unmute(self):
if not self.muteAgents: return
global OLD_STDOUT, OLD_STDERR
# Revert stdout/stderr to originals
sys.stdout = OLD_STDOUT
sys.stderr = OLD_STDERR
def run( self ):
"""
Main control loop for game play.
"""
self.display.initialize(self.state.data)
self.numMoves = 0
###self.display.initialize(self.state.makeObservation(1).data)
# inform learning agents of the game start
for i in range(len(self.agents)):
agent = self.agents[i]
if not agent:
self.mute(i)
# this is a null agent, meaning it failed to load
# the other team wins
print >>sys.stderr, "Agent %d failed to load" % i
self.unmute()
self._agentCrash(i, quiet=True)
return
if ("registerInitialState" in dir(agent)):
self.mute(i)
if self.catchExceptions:
try:
timed_func = TimeoutFunction(agent.registerInitialState, int(self.rules.getMaxStartupTime(i)))
try:
start_time = time.time()
timed_func(self.state.deepCopy())
time_taken = time.time() - start_time
self.totalAgentTimes[i] += time_taken
except TimeoutFunctionException:
print >>sys.stderr, "Agent %d ran out of time on startup!" % i
self.unmute()
self.agentTimeout = True
self._agentCrash(i, quiet=True)
return
except Exception,data:
self._agentCrash(i, quiet=False)
self.unmute()
return
else:
agent.registerInitialState(self.state.deepCopy())
## TODO: could this exceed the total time
self.unmute()
agentIndex = self.startingIndex
numAgents = len( self.agents )
while not self.gameOver:
# Fetch the next agent
agent = self.agents[agentIndex]
move_time = 0
skip_action = False
# Generate an observation of the state
if 'observationFunction' in dir( agent ):
self.mute(agentIndex)
if self.catchExceptions:
try:
timed_func = TimeoutFunction(agent.observationFunction, int(self.rules.getMoveTimeout(agentIndex)))
try:
start_time = time.time()
observation = timed_func(self.state.deepCopy())
except TimeoutFunctionException:
skip_action = True
move_time += time.time() - start_time
self.unmute()
except Exception,data:
self._agentCrash(agentIndex, quiet=False)
self.unmute()
return
else:
observation = agent.observationFunction(self.state.deepCopy())
self.unmute()
else:
observation = self.state.deepCopy()
# Solicit an action
action = None
self.mute(agentIndex)
if self.catchExceptions:
try:
timed_func = TimeoutFunction(agent.getAction, int(self.rules.getMoveTimeout(agentIndex)) - int(move_time))
try:
start_time = time.time()
if skip_action:
raise TimeoutFunctionException()
action = timed_func( observation )
except TimeoutFunctionException:
print >>sys.stderr, "Agent %d timed out on a single move!" % agentIndex
self.agentTimeout = True
self._agentCrash(agentIndex, quiet=True)
self.unmute()
return
move_time += time.time() - start_time
if move_time > self.rules.getMoveWarningTime(agentIndex):
self.totalAgentTimeWarnings[agentIndex] += 1
print >>sys.stderr, "Agent %d took too long to make a move! This is warning %d" % (agentIndex, self.totalAgentTimeWarnings[agentIndex])
if self.totalAgentTimeWarnings[agentIndex] > self.rules.getMaxTimeWarnings(agentIndex):
print >>sys.stderr, "Agent %d exceeded the maximum number of warnings: %d" % (agentIndex, self.totalAgentTimeWarnings[agentIndex])
self.agentTimeout = True
self._agentCrash(agentIndex, quiet=True)
self.unmute()
return
self.totalAgentTimes[agentIndex] += move_time
#print "Agent: %d, time: %f, total: %f" % (agentIndex, move_time, self.totalAgentTimes[agentIndex])
if self.totalAgentTimes[agentIndex] > self.rules.getMaxTotalTime(agentIndex):
print >>sys.stderr, "Agent %d ran out of time! (time: %1.2f)" % (agentIndex, self.totalAgentTimes[agentIndex])
self.agentTimeout = True
self._agentCrash(agentIndex, quiet=True)
self.unmute()
return
self.unmute()
except Exception,data:
self._agentCrash(agentIndex)
self.unmute()
return
else:
action = agent.getAction(observation)
self.unmute()
# Execute the action
self.moveHistory.append( (agentIndex, action) )
if self.catchExceptions:
try:
self.state = self.state.generateSuccessor( agentIndex, action )
except Exception,data:
self.mute(agentIndex)
self._agentCrash(agentIndex)
self.unmute()
return
else:
self.state = self.state.generateSuccessor( agentIndex, action )
# Change the display
self.display.update( self.state.data )
###idx = agentIndex - agentIndex % 2 + 1
###self.display.update( self.state.makeObservation(idx).data )
# Allow for game specific conditions (winning, losing, etc.)
self.rules.process(self.state, self)
# Track progress
if agentIndex == numAgents + 1: self.numMoves += 1
# Next agent
agentIndex = ( agentIndex + 1 ) % numAgents
if _BOINC_ENABLED:
boinc.set_fraction_done(self.getProgress())
# inform a learning agent of the game result
for agentIndex, agent in enumerate(self.agents):
if "final" in dir( agent ) :
try:
self.mute(agentIndex)
agent.final( self.state )
self.unmute()
except Exception,data:
if not self.catchExceptions: raise
self._agentCrash(agentIndex)
self.unmute()
return
self.display.finish()
================================================
FILE: Project-1/ghostAgents.py
================================================
# ghostAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import Agent
from game import Actions
from game import Directions
import random
from util import manhattanDistance
import util
class GhostAgent( Agent ):
def __init__( self, index ):
self.index = index
def getAction( self, state ):
dist = self.getDistribution(state)
if len(dist) == 0:
return Directions.STOP
else:
return util.chooseFromDistribution( dist )
def getDistribution(self, state):
"Returns a Counter encoding a distribution over actions from the provided state."
util.raiseNotDefined()
class RandomGhost( GhostAgent ):
"A ghost that chooses a legal action uniformly at random."
def getDistribution( self, state ):
dist = util.Counter()
for a in state.getLegalActions( self.index ): dist[a] = 1.0
dist.normalize()
return dist
class DirectionalGhost( GhostAgent ):
"A ghost that prefers to rush Pacman, or flee when scared."
def __init__( self, index, prob_attack=0.8, prob_scaredFlee=0.8 ):
self.index = index
self.prob_attack = prob_attack
self.prob_scaredFlee = prob_scaredFlee
def getDistribution( self, state ):
# Read variables from state
ghostState = state.getGhostState( self.index )
legalActions = state.getLegalActions( self.index )
pos = state.getGhostPosition( self.index )
isScared = ghostState.scaredTimer > 0
speed = 1
if isScared: speed = 0.5
actionVectors = [Actions.directionToVector( a, speed ) for a in legalActions]
newPositions = [( pos[0]+a[0], pos[1]+a[1] ) for a in actionVectors]
pacmanPosition = state.getPacmanPosition()
# Select best actions given the state
distancesToPacman = [manhattanDistance( pos, pacmanPosition ) for pos in newPositions]
if isScared:
bestScore = max( distancesToPacman )
bestProb = self.prob_scaredFlee
else:
bestScore = min( distancesToPacman )
bestProb = self.prob_attack
bestActions = [action for action, distance in zip( legalActions, distancesToPacman ) if distance == bestScore]
# Construct distribution
dist = util.Counter()
for a in bestActions: dist[a] = bestProb / len(bestActions)
for a in legalActions: dist[a] += ( 1-bestProb ) / len(legalActions)
dist.normalize()
return dist
================================================
FILE: Project-1/grading.py
================================================
# grading.py
# ----------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"Common code for autograders"
import cgi
import time
import sys
import traceback
import pdb
from collections import defaultdict
import util
class Grades:
"A data structure for project grades, along with formatting code to display them"
def __init__(self, projectName, questionsAndMaxesList, edxOutput=False, muteOutput=False):
"""
Defines the grading scheme for a project
projectName: project name
questionsAndMaxesDict: a list of (question name, max points per question)
"""
self.questions = [el[0] for el in questionsAndMaxesList]
self.maxes = dict(questionsAndMaxesList)
self.points = Counter()
self.messages = dict([(q, []) for q in self.questions])
self.project = projectName
self.start = time.localtime()[1:6]
self.sane = True # Sanity checks
self.currentQuestion = None # Which question we're grading
self.edxOutput = edxOutput
self.mute = muteOutput
self.prereqs = defaultdict(set)
#print 'Autograder transcript for %s' % self.project
print 'Starting on %d-%d at %d:%02d:%02d' % self.start
def addPrereq(self, question, prereq):
self.prereqs[question].add(prereq)
def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
"""
Grades each question
gradingModule: the module with all the grading functions (pass in with sys.modules[__name__])
"""
completedQuestions = set([])
for q in self.questions:
print '\nQuestion %s' % q
print '=' * (9 + len(q))
print
self.currentQuestion = q
incompleted = self.prereqs[q].difference(completedQuestions)
if len(incompleted) > 0:
prereq = incompleted.pop()
print \
"""*** NOTE: Make sure to complete Question %s before working on Question %s,
*** because Question %s builds upon your answer for Question %s.
""" % (prereq, q, q, prereq)
continue
if self.mute: util.mutePrint()
try:
util.TimeoutFunction(getattr(gradingModule, q),300)(self) # Call the question's function
#TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function
except Exception, inst:
self.addExceptionMessage(q, inst, traceback)
self.addErrorHints(exceptionMap, inst, q[1])
except:
self.fail('FAIL: Terminated with a string exception.')
finally:
if self.mute: util.unmutePrint()
if self.points[q] >= self.maxes[q]:
completedQuestions.add(q)
print '\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])
print '\nFinished at %d:%02d:%02d' % time.localtime()[3:6]
print "\nProvisional grades\n=================="
for q in self.questions:
print 'Question %s: %d/%d' % (q, self.points[q], self.maxes[q])
print '------------------'
print 'Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))
if bonusPic and self.points.totalCount() == 25:
print """
ALL HAIL GRANDPAC.
LONG LIVE THE GHOSTBUSTING KING.
--- ---- ---
| \ / + \ / |
| + \--/ \--/ + |
| + + |
| + + + |
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ / @@@@@@@@@@@@@@@@@@@@@@@@@@
V @@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
/\ @@@@@@@@@@@@@@@@@@@@@@
/ \ @@@@@@@@@@@@@@@@@@@@@@@@@
/\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@
/ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
"""
print """
Your grades are NOT yet registered. To register your grades, make sure
to follow your instructor's guidelines to receive credit on your project.
"""
if self.edxOutput:
self.produceOutput()
def addExceptionMessage(self, q, inst, traceback):
"""
Method to format the exception message, this is more complicated because
we need to cgi.escape the traceback but wrap the exception in a <pre> tag
"""
self.fail('FAIL: Exception raised: %s' % inst)
self.addMessage('')
for line in traceback.format_exc().split('\n'):
self.addMessage(line)
def addErrorHints(self, exceptionMap, errorInstance, questionNum):
typeOf = str(type(errorInstance))
questionName = 'q' + questionNum
errorHint = ''
# question specific error hints
if exceptionMap.get(questionName):
questionMap = exceptionMap.get(questionName)
if (questionMap.get(typeOf)):
errorHint = questionMap.get(typeOf)
# fall back to general error messages if a question specific
# one does not exist
if (exceptionMap.get(typeOf)):
errorHint = exceptionMap.get(typeOf)
# dont include the HTML if we have no error hint
if not errorHint:
return ''
for line in errorHint.split('\n'):
self.addMessage(line)
def produceOutput(self):
edxOutput = open('edx_response.html', 'w')
edxOutput.write("<div>")
# first sum
total_possible = sum(self.maxes.values())
total_score = sum(self.points.values())
checkOrX = '<span class="incorrect"/>'
if (total_score >= total_possible):
checkOrX = '<span class="correct"/>'
header = """
<h3>
Total score ({total_score} / {total_possible})
</h3>
""".format(total_score = total_score,
total_possible = total_possible,
checkOrX = checkOrX
)
edxOutput.write(header)
for q in self.questions:
if len(q) == 2:
name = q[1]
else:
name = q
checkOrX = '<span class="incorrect"/>'
if (self.points[q] == self.maxes[q]):
checkOrX = '<span class="correct"/>'
#messages = '\n<br/>\n'.join(self.messages[q])
messages = "<pre>%s</pre>" % '\n'.join(self.messages[q])
output = """
<div class="test">
<section>
<div class="shortform">
Question {q} ({points}/{max}) {checkOrX}
</div>
<div class="longform">
{messages}
</div>
</section>
</div>
""".format(q = name,
max = self.maxes[q],
messages = messages,
checkOrX = checkOrX,
points = self.points[q]
)
# print "*** output for Question %s " % q[1]
# print output
edxOutput.write(output)
edxOutput.write("</div>")
edxOutput.close()
edxOutput = open('edx_grade', 'w')
edxOutput.write(str(self.points.totalCount()))
edxOutput.close()
def fail(self, message, raw=False):
"Sets sanity check bit to false and outputs a message"
self.sane = False
self.assignZeroCredit()
self.addMessage(message, raw)
def assignZeroCredit(self):
self.points[self.currentQuestion] = 0
def addPoints(self, amt):
self.points[self.currentQuestion] += amt
def deductPoints(self, amt):
self.points[self.currentQuestion] -= amt
def assignFullCredit(self, message="", raw=False):
self.points[self.currentQuestion] = self.maxes[self.currentQuestion]
if message != "":
self.addMessage(message, raw)
def addMessage(self, message, raw=False):
if not raw:
# We assume raw messages, formatted for HTML, are printed separately
if self.mute: util.unmutePrint()
print '*** ' + message
if self.mute: util.mutePrint()
message = cgi.escape(message)
self.messages[self.currentQuestion].append(message)
def addMessageToEmail(self, message):
print "WARNING**** addMessageToEmail is deprecated %s" % message
for line in message.split('\n'):
pass
#print '%%% ' + line + ' %%%'
#self.messages[self.currentQuestion].append(line)
class Counter(dict):
"""
Dict with default 0
"""
def __getitem__(self, idx):
try:
return dict.__getitem__(self, idx)
except KeyError:
return 0
def totalCount(self):
"""
Returns the sum of counts for all keys.
"""
return sum(self.values())
================================================
FILE: Project-1/graphicsDisplay.py
================================================
# graphicsDisplay.py
# ------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from graphicsUtils import *
import math, time
from game import Directions
###########################
# GRAPHICS DISPLAY CODE #
###########################
# Most code by Dan Klein and John Denero written or rewritten for cs188, UC Berkeley.
# Some code from a Pacman implementation by LiveWires, and used / modified with permission.
DEFAULT_GRID_SIZE = 30.0
INFO_PANE_HEIGHT = 35
BACKGROUND_COLOR = formatColor(0,0,0)
WALL_COLOR = formatColor(0.0/255.0, 51.0/255.0, 255.0/255.0)
INFO_PANE_COLOR = formatColor(.4,.4,0)
SCORE_COLOR = formatColor(.9, .9, .9)
PACMAN_OUTLINE_WIDTH = 2
PACMAN_CAPTURE_OUTLINE_WIDTH = 4
GHOST_COLORS = []
GHOST_COLORS.append(formatColor(.9,0,0)) # Red
GHOST_COLORS.append(formatColor(0,.3,.9)) # Blue
GHOST_COLORS.append(formatColor(.98,.41,.07)) # Orange
GHOST_COLORS.append(formatColor(.1,.75,.7)) # Green
GHOST_COLORS.append(formatColor(1.0,0.6,0.0)) # Yellow
GHOST_COLORS.append(formatColor(.4,0.13,0.91)) # Purple
TEAM_COLORS = GHOST_COLORS[:2]
GHOST_SHAPE = [
( 0, 0.3 ),
( 0.25, 0.75 ),
( 0.5, 0.3 ),
( 0.75, 0.75 ),
( 0.75, -0.5 ),
( 0.5, -0.75 ),
(-0.5, -0.75 ),
(-0.75, -0.5 ),
(-0.75, 0.75 ),
(-0.5, 0.3 ),
(-0.25, 0.75 )
]
GHOST_SIZE = 0.65
SCARED_COLOR = formatColor(1,1,1)
GHOST_VEC_COLORS = map(colorToVector, GHOST_COLORS)
PACMAN_COLOR = formatColor(255.0/255.0,255.0/255.0,61.0/255)
PACMAN_SCALE = 0.5
#pacman_speed = 0.25
# Food
FOOD_COLOR = formatColor(1,1,1)
FOOD_SIZE = 0.1
# Laser
LASER_COLOR = formatColor(1,0,0)
LASER_SIZE = 0.02
# Capsule graphics
CAPSULE_COLOR = formatColor(1,1,1)
CAPSULE_SIZE = 0.25
# Drawing walls
WALL_RADIUS = 0.15
class InfoPane:
def __init__(self, layout, gridSize):
self.gridSize = gridSize
self.width = (layout.width) * gridSize
self.base = (layout.height + 1) * gridSize
self.height = INFO_PANE_HEIGHT
self.fontSize = 24
self.textColor = PACMAN_COLOR
self.drawPane()
def toScreen(self, pos, y = None):
"""
Translates a point relative from the bottom left of the info pane.
"""
if y == None:
x,y = pos
else:
x = pos
x = self.gridSize + x # Margin
y = self.base + y
return x,y
def drawPane(self):
self.scoreText = text( self.toScreen(0, 0 ), self.textColor, "SCORE: 0", "Times", self.fontSize, "bold")
def initializeGhostDistances(self, distances):
self.ghostDistanceText = []
size = 20
if self.width < 240:
size = 12
if self.width < 160:
size = 10
for i, d in enumerate(distances):
t = text( self.toScreen(self.width/2 + self.width/8 * i, 0), GHOST_COLORS[i+1], d, "Times", size, "bold")
self.ghostDistanceText.append(t)
def updateScore(self, score):
changeText(self.scoreText, "SCORE: % 4d" % score)
def setTeam(self, isBlue):
text = "RED TEAM"
if isBlue: text = "BLUE TEAM"
self.teamText = text( self.toScreen(300, 0 ), self.textColor, text, "Times", self.fontSize, "bold")
def updateGhostDistances(self, distances):
if len(distances) == 0: return
if 'ghostDistanceText' not in dir(self): self.initializeGhostDistances(distances)
else:
for i, d in enumerate(distances):
changeText(self.ghostDistanceText[i], d)
def drawGhost(self):
pass
def drawPacman(self):
pass
def drawWarning(self):
pass
def clearIcon(self):
pass
def updateMessage(self, message):
pass
def clearMessage(self):
pass
class PacmanGraphics:
def __init__(self, zoom=1.0, frameTime=0.0, capture=False):
self.have_window = 0
self.currentGhostImages = {}
self.pacmanImage = None
self.zoom = zoom
self.gridSize = DEFAULT_GRID_SIZE * zoom
self.capture = capture
self.frameTime = frameTime
def checkNullDisplay(self):
return False
def initialize(self, state, isBlue = False):
self.isBlue = isBlue
self.startGraphics(state)
# self.drawDistributions(state)
self.distributionImages = None # Initialized lazily
self.drawStaticObjects(state)
self.drawAgentObjects(state)
# Information
self.previousState = state
def startGraphics(self, state):
self.layout = state.layout
layout = self.layout
self.width = layout.width
self.height = layout.height
self.make_window(self.width, self.height)
self.infoPane = InfoPane(layout, self.gridSize)
self.currentState = layout
def drawDistributions(self, state):
walls = state.layout.walls
dist = []
for x in range(walls.width):
distx = []
dist.append(distx)
for y in range(walls.height):
( screen_x, screen_y ) = self.to_screen( (x, y) )
block = square( (screen_x, screen_y),
0.5 * self.gridSize,
color = BACKGROUND_COLOR,
filled = 1, behind=2)
distx.append(block)
self.distributionImages = dist
def drawStaticObjects(self, state):
layout = self.layout
self.drawWalls(layout.walls)
self.food = self.drawFood(layout.food)
self.capsules = self.drawCapsules(layout.capsules)
refresh()
def drawAgentObjects(self, state):
self.agentImages = [] # (agentState, image)
for index, agent in enumerate(state.agentStates):
if agent.isPacman:
image = self.drawPacman(agent, index)
self.agentImages.append( (agent, image) )
else:
image = self.drawGhost(agent, index)
self.agentImages.append( (agent, image) )
refresh()
def swapImages(self, agentIndex, newState):
"""
Changes an image from a ghost to a pacman or vis versa (for capture)
"""
prevState, prevImage = self.agentImages[agentIndex]
for item in prevImage: remove_from_screen(item)
if newState.isPacman:
image = self.drawPacman(newState, agentIndex)
self.agentImages[agentIndex] = (newState, image )
else:
image = self.drawGhost(newState, agentIndex)
self.agentImages[agentIndex] = (newState, image )
refresh()
def update(self, newState):
agentIndex = newState._agentMoved
agentState = newState.agentStates[agentIndex]
if self.agentImages[agentIndex][0].isPacman != agentState.isPacman: self.swapImages(agentIndex, agentState)
prevState, prevImage = self.agentImages[agentIndex]
if agentState.isPacman:
self.animatePacman(agentState, prevState, prevImage)
else:
self.moveGhost(agentState, agentIndex, prevState, prevImage)
self.agentImages[agentIndex] = (agentState, prevImage)
if newState._foodEaten != None:
self.removeFood(newState._foodEaten, self.food)
if newState._capsuleEaten != None:
self.removeCapsule(newState._capsuleEaten, self.capsules)
self.infoPane.updateScore(newState.score)
if 'ghostDistances' in dir(newState):
self.infoPane.updateGhostDistances(newState.ghostDistances)
def make_window(self, width, height):
grid_width = (width-1) * self.gridSize
grid_height = (height-1) * self.gridSize
screen_width = 2*self.gridSize + grid_width
screen_height = 2*self.gridSize + grid_height + INFO_PANE_HEIGHT
begin_graphics(screen_width,
screen_height,
BACKGROUND_COLOR,
"CS188 Pacman")
def drawPacman(self, pacman, index):
position = self.getPosition(pacman)
screen_point = self.to_screen(position)
endpoints = self.getEndpoints(self.getDirection(pacman))
width = PACMAN_OUTLINE_WIDTH
outlineColor = PACMAN_COLOR
fillColor = PACMAN_COLOR
if self.capture:
outlineColor = TEAM_COLORS[index % 2]
fillColor = GHOST_COLORS[index]
width = PACMAN_CAPTURE_OUTLINE_WIDTH
return [circle(screen_point, PACMAN_SCALE * self.gridSize,
fillColor = fillColor, outlineColor = outlineColor,
endpoints = endpoints,
width = width)]
def getEndpoints(self, direction, position=(0,0)):
x, y = position
pos = x - int(x) + y - int(y)
width = 30 + 80 * math.sin(math.pi* pos)
delta = width / 2
if (direction == 'West'):
endpoints = (180+delta, 180-delta)
elif (direction == 'North'):
endpoints = (90+delta, 90-delta)
elif (direction == 'South'):
endpoints = (270+delta, 270-delta)
else:
endpoints = (0+delta, 0-delta)
return endpoints
def movePacman(self, position, direction, image):
screenPosition = self.to_screen(position)
endpoints = self.getEndpoints( direction, position )
r = PACMAN_SCALE * self.gridSize
moveCircle(image[0], screenPosition, r, endpoints)
refresh()
def animatePacman(self, pacman, prevPacman, image):
if self.frameTime < 0:
print 'Press any key to step forward, "q" to play'
keys = wait_for_keys()
if 'q' in keys:
self.frameTime = 0.1
if self.frameTime > 0.01 or self.frameTime < 0:
start = time.time()
fx, fy = self.getPosition(prevPacman)
px, py = self.getPosition(pacman)
frames = 4.0
for i in range(1,int(frames) + 1):
pos = px*i/frames + fx*(frames-i)/frames, py*i/frames + fy*(frames-i)/frames
self.movePacman(pos, self.getDirection(pacman), image)
refresh()
sleep(abs(self.frameTime) / frames)
else:
self.movePacman(self.getPosition(pacman), self.getDirection(pacman), image)
refresh()
def getGhostColor(self, ghost, ghostIndex):
if ghost.scaredTimer > 0:
return SCARED_COLOR
else:
return GHOST_COLORS[ghostIndex]
def drawGhost(self, ghost, agentIndex):
pos = self.getPosition(ghost)
dir = self.getDirection(ghost)
(screen_x, screen_y) = (self.to_screen(pos) )
coords = []
for (x, y) in GHOST_SHAPE:
coords.append((x*self.gridSize*GHOST_SIZE + screen_x, y*self.gridSize*GHOST_SIZE + screen_y))
colour = self.getGhostColor(ghost, agentIndex)
body = polygon(coords, colour, filled = 1)
WHITE = formatColor(1.0, 1.0, 1.0)
BLACK = formatColor(0.0, 0.0, 0.0)
dx = 0
dy = 0
if dir == 'North':
dy = -0.2
if dir == 'South':
dy = 0.2
if dir == 'East':
dx = 0.2
if dir == 'West':
dx = -0.2
leftEye = circle((screen_x+self.gridSize*GHOST_SIZE*(-0.3+dx/1.5), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy/1.5)), self.gridSize*GHOST_SIZE*0.2, WHITE, WHITE)
rightEye = circle((screen_x+self.gridSize*GHOST_SIZE*(0.3+dx/1.5), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy/1.5)), self.gridSize*GHOST_SIZE*0.2, WHITE, WHITE)
leftPupil = circle((screen_x+self.gridSize*GHOST_SIZE*(-0.3+dx), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy)), self.gridSize*GHOST_SIZE*0.08, BLACK, BLACK)
rightPupil = circle((screen_x+self.gridSize*GHOST_SIZE*(0.3+dx), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy)), self.gridSize*GHOST_SIZE*0.08, BLACK, BLACK)
ghostImageParts = []
ghostImageParts.append(body)
ghostImageParts.append(leftEye)
ghostImageParts.append(rightEye)
ghostImageParts.append(leftPupil)
ghostImageParts.append(rightPupil)
return ghostImageParts
def moveEyes(self, pos, dir, eyes):
(screen_x, screen_y) = (self.to_screen(pos) )
dx = 0
dy = 0
if dir == 'North':
dy = -0.2
if dir == 'South':
dy = 0.2
if dir == 'East':
dx = 0.2
if dir == 'West':
dx = -0.2
moveCircle(eyes[0],(screen_x+self.gridSize*GHOST_SIZE*(-0.3+dx/1.5), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy/1.5)), self.gridSize*GHOST_SIZE*0.2)
moveCircle(eyes[1],(screen_x+self.gridSize*GHOST_SIZE*(0.3+dx/1.5), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy/1.5)), self.gridSize*GHOST_SIZE*0.2)
moveCircle(eyes[2],(screen_x+self.gridSize*GHOST_SIZE*(-0.3+dx), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy)), self.gridSize*GHOST_SIZE*0.08)
moveCircle(eyes[3],(screen_x+self.gridSize*GHOST_SIZE*(0.3+dx), screen_y-self.gridSize*GHOST_SIZE*(0.3-dy)), self.gridSize*GHOST_SIZE*0.08)
def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
old_x, old_y = self.to_screen(self.getPosition(prevGhost))
new_x, new_y = self.to_screen(self.getPosition(ghost))
delta = new_x - old_x, new_y - old_y
for ghostImagePart in ghostImageParts:
move_by(ghostImagePart, delta)
refresh()
if ghost.scaredTimer > 0:
color = SCARED_COLOR
else:
color = GHOST_COLORS[ghostIndex]
edit(ghostImageParts[0], ('fill', color), ('outline', color))
self.moveEyes(self.getPosition(ghost), self.getDirection(ghost), ghostImageParts[-4:])
refresh()
def getPosition(self, agentState):
if agentState.configuration == None: return (-1000, -1000)
return agentState.getPosition()
def getDirection(self, agentState):
if agentState.configuration == None: return Directions.STOP
return agentState.configuration.getDirection()
def finish(self):
end_graphics()
def to_screen(self, point):
( x, y ) = point
#y = self.height - y
x = (x + 1)*self.gridSize
y = (self.height - y)*self.gridSize
return ( x, y )
# Fixes some TK issue with off-center circles
def to_screen2(self, point):
( x, y ) = point
#y = self.height - y
x = (x + 1)*self.gridSize
y = (self.height - y)*self.gridSize
return ( x, y )
def drawWalls(self, wallMatrix):
wallColor = WALL_COLOR
for xNum, x in enumerate(wallMatrix):
if self.capture and (xNum * 2) < wallMatrix.width: wallColor = TEAM_COLORS[0]
if self.capture and (xNum * 2) >= wallMatrix.width: wallColor = TEAM_COLORS[1]
for yNum, cell in enumerate(x):
if cell: # There's a wall here
pos = (xNum, yNum)
screen = self.to_screen(pos)
screen2 = self.to_screen2(pos)
# draw each quadrant of the square based on adjacent walls
wIsWall = self.isWall(xNum-1, yNum, wallMatrix)
eIsWall = self.isWall(xNum+1, yNum, wallMatrix)
nIsWall = self.isWall(xNum, yNum+1, wallMatrix)
sIsWall = self.isWall(xNum, yNum-1, wallMatrix)
nwIsWall = self.isWall(xNum-1, yNum+1, wallMatrix)
swIsWall = self.isWall(xNum-1, yNum-1, wallMatrix)
neIsWall = self.isWall(xNum+1, yNum+1, wallMatrix)
seIsWall = self.isWall(xNum+1, yNum-1, wallMatrix)
# NE quadrant
if (not nIsWall) and (not eIsWall):
# inner circle
circle(screen2, WALL_RADIUS * self.gridSize, wallColor, wallColor, (0,91), 'arc')
if (nIsWall) and (not eIsWall):
# vertical line
line(add(screen, (self.gridSize*WALL_RADIUS, 0)), add(screen, (self.gridSize*WALL_RADIUS, self.gridSize*(-0.5)-1)), wallColor)
if (not nIsWall) and (eIsWall):
# horizontal line
line(add(screen, (0, self.gridSize*(-1)*WALL_RADIUS)), add(screen, (self.gridSize*0.5+1, self.gridSize*(-1)*WALL_RADIUS)), wallColor)
if (nIsWall) and (eIsWall) and (not neIsWall):
# outer circle
circle(add(screen2, (self.gridSize*2*WALL_RADIUS, self.gridSize*(-2)*WALL_RADIUS)), WALL_RADIUS * self.gridSize-1, wallColor, wallColor, (180,271), 'arc')
line(add(screen, (self.gridSize*2*WALL_RADIUS-1, self.gridSize*(-1)*WALL_RADIUS)), add(screen, (self.gridSize*0.5+1, self.gridSize*(-1)*WALL_RADIUS)), wallColor)
line(add(screen, (self.gridSize*WALL_RADIUS, self.gridSize*(-2)*WALL_RADIUS+1)), add(screen, (self.gridSize*WALL_RADIUS, self.gridSize*(-0.5))), wallColor)
# NW quadrant
if (not nIsWall) and (not wIsWall):
# inner circle
circle(screen2, WALL_RADIUS * self.gridSize, wallColor, wallColor, (90,181), 'arc')
if (nIsWall) and (not wIsWall):
# vertical line
line(add(screen, (self.gridSize*(-1)*WALL_RADIUS, 0)), add(screen, (self.gridSize*(-1)*WALL_RADIUS, self.gridSize*(-0.5)-1)), wallColor)
if (not nIsWall) and (wIsWall):
# horizontal line
line(add(screen, (0, self.gridSize*(-1)*WALL_RADIUS)), add(screen, (self.gridSize*(-0.5)-1, self.gridSize*(-1)*WALL_RADIUS)), wallColor)
if (nIsWall) and (wIsWall) and (not nwIsWall):
# outer circle
circle(add(screen2, (self.gridSize*(-2)*WALL_RADIUS, self.gridSize*(-2)*WALL_RADIUS)), WALL_RADIUS * self.gridSize-1, wallColor, wallColor, (270,361), 'arc')
line(add(screen, (self.gridSize*(-2)*WALL_RADIUS+1, self.gridSize*(-1)*WALL_RADIUS)), add(screen, (self.gridSize*(-0.5), self.gridSize*(-1)*WALL_RADIUS)), wallColor)
line(add(screen, (self.gridSize*(-1)*WALL_RADIUS, self.gridSize*(-2)*WALL_RADIUS+1)), add(screen, (self.gridSize*(-1)*WALL_RADIUS, self.gridSize*(-0.5))), wallColor)
# SE quadrant
if (not sIsWall) and (not eIsWall):
# inner circle
circle(screen2, WALL_RADIUS * self.gridSize, wallColor, wallColor, (270,361), 'arc')
if (sIsWall) and (not eIsWall):
# vertical line
line(add(screen, (self.gridSize*WALL_RADIUS, 0)), add(screen, (self.gridSize*WALL_RADIUS, self.gridSize*(0.5)+1)), wallColor)
if (not sIsWall) and (eIsWall):
# horizontal line
line(add(screen, (0, self.gridSize*(1)*WALL_RADIUS)), add(screen, (self.gridSize*0.5+1, self.gridSize*(1)*WALL_RADIUS)), wallColor)
if (sIsWall) and (eIsWall) and (not seIsWall):
# outer circle
circle(add(screen2, (self.gridSize*2*WALL_RADIUS, self.gridSize*(2)*WALL_RADIUS)), WALL_RADIUS * self.gridSize-1, wallColor, wallColor, (90,181), 'arc')
line(add(screen, (self.gridSize*2*WALL_RADIUS-1, self.gridSize*(1)*WALL_RADIUS)), add(screen, (self.gridSize*0.5, self.gridSize*(1)*WALL_RADIUS)), wallColor)
line(add(screen, (self.gridSize*WALL_RADIUS, self.gridSize*(2)*WALL_RADIUS-1)), add(screen, (self.gridSize*WALL_RADIUS, self.gridSize*(0.5))), wallColor)
# SW quadrant
if (not sIsWall) and (not wIsWall):
# inner circle
circle(screen2, WALL_RADIUS * self.gridSize, wallColor, wallColor, (180,271), 'arc')
if (sIsWall) and (not wIsWall):
# vertical line
line(add(screen, (self.gridSize*(-1)*WALL_RADIUS, 0)), add(screen, (self.gridSize*(-1)*WALL_RADIUS, self.gridSize*(0.5)+1)), wallColor)
if (not sIsWall) and (wIsWall):
# horizontal line
line(add(screen, (0, self.gridSize*(1)*WALL_RADIUS)), add(screen, (self.gridSize*(-0.5)-1, self.gridSize*(1)*WALL_RADIUS)), wallColor)
if (sIsWall) and (wIsWall) and (not swIsWall):
# outer circle
circle(add(screen2, (self.gridSize*(-2)*WALL_RADIUS, self.gridSize*(2)*WALL_RADIUS)), WALL_RADIUS * self.gridSize-1, wallColor, wallColor, (0,91), 'arc')
line(add(screen, (self.gridSize*(-2)*WALL_RADIUS+1, self.gridSize*(1)*WALL_RADIUS)), add(screen, (self.gridSize*(-0.5), self.gridSize*(1)*WALL_RADIUS)), wallColor)
line(add(screen, (self.gridSize*(-1)*WALL_RADIUS, self.gridSize*(2)*WALL_RADIUS-1)), add(screen, (self.gridSize*(-1)*WALL_RADIUS, self.gridSize*(0.5))), wallColor)
def isWall(self, x, y, walls):
if x < 0 or y < 0:
return False
if x >= walls.width or y >= walls.height:
return False
return walls[x][y]
def drawFood(self, foodMatrix ):
foodImages = []
color = FOOD_COLOR
for xNum, x in enumerate(foodMatrix):
if self.capture and (xNum * 2) <= foodMatrix.width: color = TEAM_COLORS[0]
if self.capture and (xNum * 2) > foodMatrix.width: color = TEAM_COLORS[1]
imageRow = []
foodImages.append(imageRow)
for yNum, cell in enumerate(x):
if cell: # There's food here
screen = self.to_screen((xNum, yNum ))
dot = circle( screen,
FOOD_SIZE * self.gridSize,
outlineColor = color, fillColor = color,
width = 1)
imageRow.append(dot)
else:
imageRow.append(None)
return foodImages
def drawCapsules(self, capsules ):
capsuleImages = {}
for capsule in capsules:
( screen_x, screen_y ) = self.to_screen(capsule)
dot = circle( (screen_x, screen_y),
CAPSULE_SIZE * self.gridSize,
outlineColor = CAPSULE_COLOR,
fillColor = CAPSULE_COLOR,
width = 1)
capsuleImages[capsule] = dot
return capsuleImages
def removeFood(self, cell, foodImages ):
x, y = cell
remove_from_screen(foodImages[x][y])
def removeCapsule(self, cell, capsuleImages ):
x, y = cell
remove_from_screen(capsuleImages[(x, y)])
def drawExpandedCells(self, cells):
"""
Draws an overlay of expanded grid positions for search agents
"""
n = float(len(cells))
baseColor = [1.0, 0.0, 0.0]
self.clearExpandedCells()
self.expandedCells = []
for k, cell in enumerate(cells):
screenPos = self.to_screen( cell)
cellColor = formatColor(*[(n-k) * c * .5 / n + .25 for c in baseColor])
block = square(screenPos,
0.5 * self.gridSize,
color = cellColor,
filled = 1, behind=2)
self.expandedCells.append(block)
if self.frameTime < 0:
refresh()
def clearExpandedCells(self):
if 'expandedCells' in dir(self) and len(self.expandedCells) > 0:
for cell in self.expandedCells:
remove_from_screen(cell)
def updateDistributions(self, distributions):
"Draws an agent's belief distributions"
# copy all distributions so we don't change their state
distributions = map(lambda x: x.copy(), distributions)
if self.distributionImages == None:
self.drawDistributions(self.previousState)
for x in range(len(self.distributionImages)):
for y in range(len(self.distributionImages[0])):
image = self.distributionImages[x][y]
weights = [dist[ (x,y) ] for dist in distributions]
if sum(weights) != 0:
pass
# Fog of war
color = [0.0,0.0,0.0]
colors = GHOST_VEC_COLORS[1:] # With Pacman
if self.capture: colors = GHOST_VEC_COLORS
for weight, gcolor in zip(weights, colors):
color = [min(1.0, c + 0.95 * g * weight ** .3) for c,g in zip(color, gcolor)]
changeColor(image, formatColor(*color))
refresh()
class FirstPersonPacmanGraphics(PacmanGraphics):
def __init__(self, zoom = 1.0, showGhosts = True, capture = False, frameTime=0):
PacmanGraphics.__init__(self, zoom, frameTime=frameTime)
self.showGhosts = showGhosts
self.capture = capture
def initialize(self, state, isBlue = False):
self.isBlue = isBlue
PacmanGraphics.startGraphics(self, state)
# Initialize distribution images
walls = state.layout.walls
dist = []
self.layout = state.layout
# Draw the rest
self.distributionImages = None # initialize lazily
self.drawStaticObjects(state)
self.drawAgentObjects(state)
# Information
self.previousState = state
def lookAhead(self, config, state):
if config.getDirection() == 'Stop':
return
else:
pass
# Draw relevant ghosts
allGhosts = state.getGhostStates()
visibleGhosts = state.getVisibleGhosts()
for i, ghost in enumerate(allGhosts):
if ghost in visibleGhosts:
self.drawGhost(ghost, i)
else:
self.currentGhostImages[i] = None
def getGhostColor(self, ghost, ghostIndex):
return GHOST_COLORS[ghostIndex]
def getPosition(self, ghostState):
if not self.showGhosts and not ghostState.isPacman and ghostState.getPosition()[1] > 1:
return (-1000, -1000)
else:
return PacmanGraphics.getPosition(self, ghostState)
def add(x, y):
return (x[0] + y[0], x[1] + y[1])
# Saving graphical output
# -----------------------
# Note: to make an animated gif from this postscript output, try the command:
# convert -delay 7 -loop 1 -compress lzw -layers optimize frame* out.gif
# convert is part of imagemagick (freeware)
SAVE_POSTSCRIPT = False
POSTSCRIPT_OUTPUT_DIR = 'frames'
FRAME_NUMBER = 0
import os
def saveFrame():
"Saves the current graphical output as a postscript file"
global SAVE_POSTSCRIPT, FRAME_NUMBER, POSTSCRIPT_OUTPUT_DIR
if not SAVE_POSTSCRIPT: return
if not os.path.exists(POSTSCRIPT_OUTPUT_DIR): os.mkdir(POSTSCRIPT_OUTPUT_DIR)
name = os.path.join(POSTSCRIPT_OUTPUT_DIR, 'frame_%08d.ps' % FRAME_NUMBER)
FRAME_NUMBER += 1
writePostscript(name) # writes the current canvas
================================================
FILE: Project-1/graphicsUtils.py
================================================
# graphicsUtils.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
import sys
import math
import random
import string
import time
import types
import Tkinter
_Windows = sys.platform == 'win32' # True if on Win95/98/NT
_root_window = None # The root window for graphics output
_canvas = None # The canvas which holds graphics
_canvas_xs = None # Size of canvas object
_canvas_ys = None
_canvas_x = None # Current position on canvas
_canvas_y = None
_canvas_col = None # Current colour (set to black below)
_canvas_tsize = 12
_canvas_tserifs = 0
def formatColor(r, g, b):
return '#%02x%02x%02x' % (int(r * 255), int(g * 255), int(b * 255))
def colorToVector(color):
return map(lambda x: int(x, 16) / 256.0, [color[1:3], color[3:5], color[5:7]])
if _Windows:
_canvas_tfonts = ['times new roman', 'lucida console']
else:
_canvas_tfonts = ['times', 'lucidasans-24']
pass # XXX need defaults here
def sleep(secs):
global _root_window
if _root_window == None:
time.sleep(secs)
else:
_root_window.update_idletasks()
_root_window.after(int(1000 * secs), _root_window.quit)
_root_window.mainloop()
def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), title=None):
global _root_window, _canvas, _canvas_x, _canvas_y, _canvas_xs, _canvas_ys, _bg_color
# Check for duplicate call
if _root_window is not None:
# Lose the window.
_root_window.destroy()
# Save the canvas size parameters
_canvas_xs, _canvas_ys = width - 1, height - 1
_canvas_x, _canvas_y = 0, _canvas_ys
_bg_color = color
# Create the root window
_root_window = Tkinter.Tk()
_root_window.protocol('WM_DELETE_WINDOW', _destroy_window)
_root_window.title(title or 'Graphics Window')
_root_window.resizable(0, 0)
# Create the canvas object
try:
_canvas = Tkinter.Canvas(_root_window, width=width, height=height)
_canvas.pack()
draw_background()
_canvas.update()
except:
_root_window = None
raise
# Bind to key-down and key-up events
_root_window.bind( "<KeyPress>", _keypress )
_root_window.bind( "<KeyRelease>", _keyrelease )
_root_window.bind( "<FocusIn>", _clear_keys )
_root_window.bind( "<FocusOut>", _clear_keys )
_root_window.bind( "<Button-1>", _leftclick )
_root_window.bind( "<Button-2>", _rightclick )
_root_window.bind( "<Button-3>", _rightclick )
_root_window.bind( "<Control-Button-1>", _ctrl_leftclick)
_clear_keys()
_leftclick_loc = None
_rightclick_loc = None
_ctrl_leftclick_loc = None
def _leftclick(event):
global _leftclick_loc
_leftclick_loc = (event.x, event.y)
def _rightclick(event):
global _rightclick_loc
_rightclick_loc = (event.x, event.y)
def _ctrl_leftclick(event):
global _ctrl_leftclick_loc
_ctrl_leftclick_loc = (event.x, event.y)
def wait_for_click():
while True:
global _leftclick_loc
global _rightclick_loc
global _ctrl_leftclick_loc
if _leftclick_loc != None:
val = _leftclick_loc
_leftclick_loc = None
return val, 'left'
if _rightclick_loc != None:
val = _rightclick_loc
_rightclick_loc = None
return val, 'right'
if _ctrl_leftclick_loc != None:
val = _ctrl_leftclick_loc
_ctrl_leftclick_loc = None
return val, 'ctrl_left'
sleep(0.05)
def draw_background():
corners = [(0,0), (0, _canvas_ys), (_canvas_xs, _canvas_ys), (_canvas_xs, 0)]
polygon(corners, _bg_color, fillColor=_bg_color, filled=True, smoothed=False)
def _destroy_window(event=None):
sys.exit(0)
# global _root_window
# _root_window.destroy()
# _root_window = None
#print "DESTROY"
def end_graphics():
global _root_window, _canvas, _mouse_enabled
try:
try:
sleep(1)
if _root_window != None:
_root_window.destroy()
except SystemExit, e:
print 'Ending graphics raised an exception:', e
finally:
_root_window = None
_canvas = None
_mouse_enabled = 0
_clear_keys()
def clear_screen(background=None):
global _canvas_x, _canvas_y
_canvas.delete('all')
draw_background()
_canvas_x, _canvas_y = 0, _canvas_ys
def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, behind=0, width=1):
c = []
for coord in coords:
c.append(coord[0])
c.append(coord[1])
if fillColor == None: fillColor = outlineColor
if filled == 0: fillColor = ""
poly = _canvas.create_polygon(c, outline=outlineColor, fill=fillColor, smooth=smoothed, width=width)
if behind > 0:
_canvas.tag_lower(poly, behind) # Higher should be more visible
return poly
def square(pos, r, color, filled=1, behind=0):
x, y = pos
coords = [(x - r, y - r), (x + r, y - r), (x + r, y + r), (x - r, y + r)]
return polygon(coords, color, color, filled, 0, behind=behind)
def circle(pos, r, outlineColor, fillColor, endpoints=None, style='pieslice', width=2):
x, y = pos
x0, x1 = x - r - 1, x + r
y0, y1 = y - r - 1, y + r
if endpoints == None:
e = [0, 359]
else:
e = list(endpoints)
while e[0] > e[1]: e[1] = e[1] + 360
return _canvas.create_arc(x0, y0, x1, y1, outline=outlineColor, fill=fillColor,
extent=e[1] - e[0], start=e[0], style=style, width=width)
def image(pos, file="../../blueghost.gif"):
x, y = pos
# img = PhotoImage(file=file)
return _canvas.create_image(x, y, image = Tkinter.PhotoImage(file=file), anchor = Tkinter.NW)
def refresh():
_canvas.update_idletasks()
def moveCircle(id, pos, r, endpoints=None):
global _canvas_x, _canvas_y
x, y = pos
# x0, x1 = x - r, x + r + 1
# y0, y1 = y - r, y + r + 1
x0, x1 = x - r - 1, x + r
y0, y1 = y - r - 1, y + r
if endpoints == None:
e = [0, 359]
else:
e = list(endpoints)
while e[0] > e[1]: e[1] = e[1] + 360
edit(id, ('start', e[0]), ('extent', e[1] - e[0]))
move_to(id, x0, y0)
def edit(id, *args):
_canvas.itemconfigure(id, **dict(args))
def text(pos, color, contents, font='Helvetica', size=12, style='normal', anchor="nw"):
global _canvas_x, _canvas_y
x, y = pos
font = (font, str(size), style)
return _canvas.create_text(x, y, fill=color, text=contents, font=font, anchor=anchor)
def changeText(id, newText, font=None, size=12, style='normal'):
_canvas.itemconfigure(id, text=newText)
if font != None:
_canvas.itemconfigure(id, font=(font, '-%d' % size, style))
def changeColor(id, newColor):
_canvas.itemconfigure(id, fill=newColor)
def line(here, there, color=formatColor(0, 0, 0), width=2):
x0, y0 = here[0], here[1]
x1, y1 = there[0], there[1]
return _canvas.create_line(x0, y0, x1, y1, fill=color, width=width)
##############################################################################
### Keypress handling ########################################################
##############################################################################
# We bind to key-down and key-up events.
_keysdown = {}
_keyswaiting = {}
# This holds an unprocessed key release. We delay key releases by up to
# one call to keys_pressed() to get round a problem with auto repeat.
_got_release = None
def _keypress(event):
global _got_release
#remap_arrows(event)
_keysdown[event.keysym] = 1
_keyswaiting[event.keysym] = 1
# print event.char, event.keycode
_got_release = None
def _keyrelease(event):
global _got_release
#remap_arrows(event)
try:
del _keysdown[event.keysym]
except:
pass
_got_release = 1
def remap_arrows(event):
# TURN ARROW PRESSES INTO LETTERS (SHOULD BE IN KEYBOARD AGENT)
if event.char in ['a', 's', 'd', 'w']:
return
if event.keycode in [37, 101]: # LEFT ARROW (win / x)
event.char = 'a'
if event.keycode in [38, 99]: # UP ARROW
event.char = 'w'
if event.keycode in [39, 102]: # RIGHT ARROW
event.char = 'd'
if event.keycode in [40, 104]: # DOWN ARROW
event.char = 's'
def _clear_keys(event=None):
global _keysdown, _got_release, _keyswaiting
_keysdown = {}
_keyswaiting = {}
_got_release = None
def keys_pressed(d_o_e=Tkinter.tkinter.dooneevent,
d_w=Tkinter.tkinter.DONT_WAIT):
d_o_e(d_w)
if _got_release:
d_o_e(d_w)
return _keysdown.keys()
def keys_waiting():
global _keyswaiting
keys = _keyswaiting.keys()
_keyswaiting = {}
return keys
# Block for a list of keys...
def wait_for_keys():
keys = []
while keys == []:
keys = keys_pressed()
sleep(0.05)
return keys
def remove_from_screen(x,
d_o_e=Tkinter.tkinter.dooneevent,
d_w=Tkinter.tkinter.DONT_WAIT):
_canvas.delete(x)
d_o_e(d_w)
def _adjust_coords(coord_list, x, y):
for i in range(0, len(coord_list), 2):
coord_list[i] = coord_list[i] + x
coord_list[i + 1] = coord_list[i + 1] + y
return coord_list
def move_to(object, x, y=None,
d_o_e=Tkinter.tkinter.dooneevent,
d_w=Tkinter.tkinter.DONT_WAIT):
if y is None:
try: x, y = x
except: raise 'incomprehensible coordinates'
horiz = True
newCoords = []
current_x, current_y = _canvas.coords(object)[0:2] # first point
for coord in _canvas.coords(object):
if horiz:
inc = x - current_x
else:
inc = y - current_y
horiz = not horiz
newCoords.append(coord + inc)
_canvas.coords(object, *newCoords)
d_o_e(d_w)
def move_by(object, x, y=None,
d_o_e=Tkinter.tkinter.dooneevent,
d_w=Tkinter.tkinter.DONT_WAIT, lift=False):
if y is None:
try: x, y = x
except: raise Exception, 'incomprehensible coordinates'
horiz = True
newCoords = []
for coord in _canvas.coords(object):
if horiz:
inc = x
else:
inc = y
horiz = not horiz
newCoords.append(coord + inc)
_canvas.coords(object, *newCoords)
d_o_e(d_w)
if lift:
_canvas.tag_raise(object)
def writePostscript(filename):
"Writes the current canvas to a postscript file."
psfile = file(filename, 'w')
psfile.write(_canvas.postscript(pageanchor='sw',
y='0.c',
x='0.c'))
psfile.close()
ghost_shape = [
(0, - 0.5),
(0.25, - 0.75),
(0.5, - 0.5),
(0.75, - 0.75),
(0.75, 0.5),
(0.5, 0.75),
(- 0.5, 0.75),
(- 0.75, 0.5),
(- 0.75, - 0.75),
(- 0.5, - 0.5),
(- 0.25, - 0.75)
]
if __name__ == '__main__':
begin_graphics()
clear_screen()
ghost_shape = [(x * 10 + 20, y * 10 + 20) for x, y in ghost_shape]
g = polygon(ghost_shape, formatColor(1, 1, 1))
move_to(g, (50, 50))
circle((150, 150), 20, formatColor(0.7, 0.3, 0.0), endpoints=[15, - 15])
sleep(2)
================================================
FILE: Project-1/keyboardAgents.py
================================================
# keyboardAgents.py
# -----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import Agent
from game import Directions
import random
class KeyboardAgent(Agent):
"""
An agent controlled by the keyboard.
"""
# NOTE: Arrow keys also work.
WEST_KEY = 'a'
EAST_KEY = 'd'
NORTH_KEY = 'w'
SOUTH_KEY = 's'
STOP_KEY = 'q'
def __init__( self, index = 0 ):
self.lastMove = Directions.STOP
self.index = index
self.keys = []
def getAction( self, state):
from graphicsUtils import keys_waiting
from graphicsUtils import keys_pressed
keys = keys_waiting() + keys_pressed()
if keys != []:
self.keys = keys
legal = state.getLegalActions(self.index)
move = self.getMove(legal)
if move == Directions.STOP:
# Try to move in the same direction as before
if self.lastMove in legal:
move = self.lastMove
if (self.STOP_KEY in self.keys) and Directions.STOP in legal: move = Directions.STOP
if move not in legal:
move = random.choice(legal)
self.lastMove = move
return move
def getMove(self, legal):
move = Directions.STOP
if (self.WEST_KEY in self.keys or 'Left' in self.keys) and Directions.WEST in legal: move = Directions.WEST
if (self.EAST_KEY in self.keys or 'Right' in self.keys) and Directions.EAST in legal: move = Directions.EAST
if (self.NORTH_KEY in self.keys or 'Up' in self.keys) and Directions.NORTH in legal: move = Directions.NORTH
if (self.SOUTH_KEY in self.keys or 'Down' in self.keys) and Directions.SOUTH in legal: move = Directions.SOUTH
return move
class KeyboardAgent2(KeyboardAgent):
"""
A second agent controlled by the keyboard.
"""
# NOTE: Arrow keys also work.
WEST_KEY = 'j'
EAST_KEY = "l"
NORTH_KEY = 'i'
SOUTH_KEY = 'k'
STOP_KEY = 'u'
def getMove(self, legal):
move = Directions.STOP
if (self.WEST_KEY in self.keys) and Directions.WEST in legal: move = Directions.WEST
if (self.EAST_KEY in self.keys) and Directions.EAST in legal: move = Directions.EAST
if (self.NORTH_KEY in self.keys) and Directions.NORTH in legal: move = Directions.NORTH
if (self.SOUTH_KEY in self.keys) and Directions.SOUTH in legal: move = Directions.SOUTH
return move
================================================
FILE: Project-1/layout.py
================================================
# layout.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from util import manhattanDistance
from game import Grid
import os
import random
VISIBILITY_MATRIX_CACHE = {}
class Layout:
"""
A Layout manages the static information about the game board.
"""
def __init__(self, layoutText):
self.width = len(layoutText[0])
self.height= len(layoutText)
self.walls = Grid(self.width, self.height, False)
self.food = Grid(self.width, self.height, False)
self.capsules = []
self.agentPositions = []
self.numGhosts = 0
self.processLayoutText(layoutText)
self.layoutText = layoutText
self.totalFood = len(self.food.asList())
# self.initializeVisibilityMatrix()
def getNumGhosts(self):
return self.numGhosts
def initializeVisibilityMatrix(self):
global VISIBILITY_MATRIX_CACHE
if reduce(str.__add__, self.layoutText) not in VISIBILITY_MATRIX_CACHE:
from game import Directions
vecs = [(-0.5,0), (0.5,0),(0,-0.5),(0,0.5)]
dirs = [Directions.NORTH, Directions.SOUTH, Directions.WEST, Directions.EAST]
vis = Grid(self.width, self.height, {Directions.NORTH:set(), Directions.SOUTH:set(), Directions.EAST:set(), Directions.WEST:set(), Directions.STOP:set()})
for x in range(self.width):
for y in range(self.height):
if self.walls[x][y] == False:
for vec, direction in zip(vecs, dirs):
dx, dy = vec
nextx, nexty = x + dx, y + dy
while (nextx + nexty) != int(nextx) + int(nexty) or not self.walls[int(nextx)][int(nexty)] :
vis[x][y][direction].add((nextx, nexty))
nextx, nexty = x + dx, y + dy
self.visibility = vis
VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)] = vis
else:
self.visibility = VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)]
def isWall(self, pos):
x, col = pos
return self.walls[x][col]
def getRandomLegalPosition(self):
x = random.choice(range(self.width))
y = random.choice(range(self.height))
while self.isWall( (x, y) ):
x = random.choice(range(self.width))
y = random.choice(range(self.height))
return (x,y)
def getRandomCorner(self):
poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)]
return random.choice(poses)
def getFurthestCorner(self, pacPos):
poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)]
dist, pos = max([(manhattanDistance(p, pacPos), p) for p in poses])
return pos
def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
row, col = [int(x) for x in pacPos]
return ghostPos in self.visibility[row][col][pacDirection]
def __str__(self):
return "\n".join(self.layoutText)
def deepCopy(self):
return Layout(self.layoutText[:])
def processLayoutText(self, layoutText):
"""
Coordinates are flipped from the input format to the (x,y) convention here
The shape of the maze. Each character
represents a different type of object.
% - Wall
. - Food
o - Capsule
G - Ghost
P - Pacman
Other characters are ignored.
"""
maxY = self.height - 1
for y in range(self.height):
for x in range(self.width):
layoutChar = layoutText[maxY - y][x]
self.processLayoutChar(x, y, layoutChar)
self.agentPositions.sort()
self.agentPositions = [ ( i == 0, pos) for i, pos in self.agentPositions]
def processLayoutChar(self, x, y, layoutChar):
if layoutChar == '%':
self.walls[x][y] = True
elif layoutChar == '.':
self.food[x][y] = True
elif layoutChar == 'o':
self.capsules.append((x, y))
elif layoutChar == 'P':
self.agentPositions.append( (0, (x, y) ) )
elif layoutChar in ['G']:
self.agentPositions.append( (1, (x, y) ) )
self.numGhosts += 1
elif layoutChar in ['1', '2', '3', '4']:
self.agentPositions.append( (int(layoutChar), (x,y)))
self.numGhosts += 1
def getLayout(name, back = 2):
if name.endswith('.lay'):
layout = tryToLoad('layouts/' + name)
if layout == None: layout = tryToLoad(name)
else:
layout = tryToLoad('layouts/' + name + '.lay')
if layout == None: layout = tryToLoad(name + '.lay')
if layout == None and back >= 0:
curdir = os.path.abspath('.')
os.chdir('..')
layout = getLayout(name, back -1)
os.chdir(curdir)
return layout
def tryToLoad(fullname):
if(not os.path.exists(fullname)): return None
f = open(fullname)
try: return Layout([line.strip() for line in f])
finally: f.close()
================================================
FILE: Project-1/layouts/bigCorners.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%. % %.%
% %%%%% % %%% %%% %%%%%%% % %
% % % % % % % %
%%%%% %%%%% %%% % % % %%% %%%%% % %%%
% % % % % % % % % % % % %
% %%% % % % %%% %%%%% %%% % %%% %%% %
% % % % % % % % %
%%% %%%%%%%%% %%%%%%% %%% %%% % % % %
% % % % % % %
% % %%%%% % %%% % % %%% % %%% %%% % %
% % % % % % % % % % % % % %
% % % %%%%%%% % %%%%%%%%% %%% % %%% %
% % % % % % % % % %
%%% %%% % %%%%% %%%%% %%% %%% %%%%% %
% % % % % % % % %
% % % % % % %%% %%% %%% % % % % % %
% % % % % %% % % % % % % % % %
% % %%%%% % %%% %%% % %%% %%% %%%%%
% % % % % % % % % % %
% %%% % % % %%% %%% %%%%%%%%% % %%%
% % % % % % %
% %%% %%%%%%%%%%%%%%%%%%%%% % % %%% %
% % % %
% % % %%%%% %%% % % % % %%%%%%%%%%%%%
% % % % % % % % % % % %
% % %%% %%% % % % %%%%%%%%% %%% % % %
% % % % % % %P % % % % % %
% %%% %%% %%% % %%% % % %%%%% % %%%%%
% % % % % % % %
%%% % %%%%% %%%%% %%% %%% % %%% % %%%
% % % % % % % % % % % % % % %
% % %%% % % % % %%%%%%%%% % % % % % %
% % % %
% % % %%% %%% %%%%%%% %%% %%% %%% %
%.% % % % % .%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/bigMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % % % % % % %
% %%%%%%% % %%% % %%% %%% %%%%%%% % %
% % % % % % % %
%%%%% %%%%% %%% % % % %%% %%%%% % %%%
% % % % % % % % % % % % % %
% %%% % % % %%% %%%%% %%% % %%% %%% %
% % % % % % % % %
%%% %%%%%%%%% %%%%%%% %%% %%% % % % %
% % % % % % %
% % %%%%% % %%% % % %%% % %%% %%% % %
% % % % % % % % % % % % % %
% % % %%%%%%% % %%%%%%%%% %%% % %%% %
% % % % % % % % % %
%%% %%% % %%%%% %%%%% %%% %%% %%%%% %
% % % % % % % % % % % %
% % % % % %%% %%% %%% %%% % % % % % %
% % % % % % % % %
%%% %%%%%%% % % %%%%% %%% % %%% %%%%%
% % % % % % % % % %
%%%%% % % %%%%%%%%% %%%%%%%%%%% % %%%
% % % % % % % % %
% %%% %%%%% %%%%%%%%% %%%%% % % %%% %
% % % % % % %
% % % %%%%% %%% % % % % %%%%%%%%%%%%%
% % % % % % % % % % % %
% % %%% %%% % % % %%%%%%%%% %%% % % %
% % % % % % % % % % % % %
% %%% %%% %%%%% %%% % % %%%%% % %%%%%
% % % % % % % % %
%%% % %%%%% %%%%% %%% %%% % %%% % %%%
% % % % % % % % % % % % % % %
% % %%% % % % % %%%%%%%%% % % % % % %
% % % % % %
% % % % %%% %%% %%%%%%% %%% %%% %%% %
%.% % % % % % % % P%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/bigSafeSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%.%.........%% G % o%%%%.....%
%.%.%%%%%%%.%%%%%% %%%%%%%.%%.%
%............%...%............%
%%%%%...%%%.. ..%.%...%.%%%
%o%%%.%%%%%.%%%%%%%.%%%.%.%%%%%
% ..........Po...%...%. o%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/bigSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%.....%.................%.....%
%.%%%.%.%%%.%%%%%%%.%%%.%.....%
%.%...%.%......%......%.%.....%
%...%%%.%.%%%%.%.%%%%...%%%...%
%%%.%.%.%.%......%..%.%...%.%%%
%...%.%%%.%.%%% %%%.%.%%%.%...%
%.%%%.......% %.......%%%.%
%...%.%%%%%.%%%%%%%.%.%%%.%...%
%%%.%...%.%....%....%.%...%.%%%
%...%%%.%.%%%%.%.%%%%.%.%%%...%
%.......%......%......%.....%.%
%.....%.%%%.%%%%%%%.%%%.%.%%%.%
%.....%........P....%...%.....%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/boxSearch.lay
================================================
%%%%%%%%%%%%%%
%. . . . . % %
% % %
%. . . . . %G%
% % %
%. . . . . % %
% % %
%. . . . . % %
% P %G%
%. . . . . % %
% % %
%. . . . . % %
% % %
%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/capsuleClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%
%G. G ....%
%.% % %%%%%% %.%%.%
%.%o% % o% %.o%.%
%.%%%.% %%% %..%.%
%..... P %..%G%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/contestClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%o...%........%...o%
%.%%.%.%%..%%.%.%%.%
%...... G GG%......%
%.%.%%.%% %%%.%%.%.%
%.%....% ooo%.%..%.%
%.%.%%.% %% %.%.%%.%
%o%......P....%....%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/contoursMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% %
% P %
% %
% %
% %
%. %
%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/greedySearch.lay
================================================
%%%%%%
%....%
% %%.%
% %%.%
%.P .%
%.%%%%
%....%
%%%%%%
================================================
FILE: Project-1/layouts/mediumClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%o...%........%....%
%.%%.%.%%%%%%.%.%%.%
%.%..............%.%
%.%.%%.%% %%.%%.%.%
%......%G G%......%
%.%.%%.%%%%%%.%%.%.%
%.%..............%.%
%.%%.%.%%%%%%.%.%%.%
%....%...P....%...o%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/mediumCorners.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%. % % % %.%
% % % %%%%%% %%%%%%% % %
% % % % % %
%%%%% %%%%% %%% %% %%%%% % %%%
% % % % % % % % %
% %%% % % % %%%%%%%% %%% %%% %
% % %% % % % %
%%% % %%%%%%% %%%% %%% % % % %
% % %% % % %
% % %%%%% % %%%% % %%% %%% % %
% % % % % % %%% %
%. %P%%%%% % %%% % .%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/mediumDottedMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% P%
% %%%%%%%%%%%%%%%%%%% %%% %%%%%%%% %
% %% % % %%% %%% %% ... %
% %% % % % % %%%% %%%%%%%%% %% %%%%%
% %% % % % % % %% %% %% ... %
% %% % % % % % %%%% %%% %%%%%% %
% % % % % % %% %%%%%%%% ... %
% %% % % %%%%%%%% %% %% %%%%%
% %% % %% %%%%%%%%% %% ... %
% %%%%%% %%%%%%% %% %%%%%% %
%%%%%% % %%%% %% % ... %
% %%%%%% %%%%% % %% %% %%%%%
% %%%%%% % %%%%% %% %
% %%%%%% %%%%%%%%%%% %% %% %
%%%%%%%%%% %%%%%% %
%. %%%%%%%%%%%%%%%% ...... %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/mediumMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% P%
% %%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% %
% %% % % %%%%%%% %% %
% %% % % % % %%%% %%%%%%%%% %% %%%%%
% %% % % % % %% %% %
% %% % % % % % %%%% %%% %%%%%% %
% % % % % % %% %%%%%%%% %
% %% % % %%%%%%%% %% %% %%%%%
% %% % %% %%%%%%%%% %% %
% %%%%%% %%%%%%% %% %%%%%% %
%%%%%% % %%%% %% % %
% %%%%%% %%%%% % %% %% %%%%%
% %%%%%% % %%%%% %% %
% %%%%%% %%%%%%%%%%% %% %% %
%%%%%%%%%% %%%%%% %
%. %%%%%%%%%%%%%%%% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/mediumSafeSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%.% ....%% G %%%%%% o%%.%
%.%o%%%%%%%.%%%%%%% %%%%%.%
% %%%.%%%%%.%%%%%%%.%%%.%.%%%.%
% ..........Po...%.........%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/mediumScaryMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% P%
% %%%%%%%%%%%%%%%%%%% %%% %%%%%%%% %
% %% % % %%% %%% %%GG %
% %% % % % % %%%% %%%%%%%%% %% %%%%%
% %% % % % % % %%GG %% %
% %% % % % % % %%%%% %%% %%%%%% %
% %% % % % % %% %%%%%%%%% %
% %% % % %%%%%%%% %% %% %%%%%
% %% % %% %%%%%%%%% %% %
% %%% %% %%%%%%% %% %%%%%% %
%%%%%% % % %% %% %
% %%%%%% %% %% %% %% %%%%%
% %%%%%% % %%%%% %% %
% %%%% %%%%% %%%%%% %
%%%%%%%% % %%%%%% %
%. %%%%%%%%%%%%%%%% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/mediumSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%............%%%%%............%
%%%.%...%%%.........%.%...%.%%%
%...%%%.%.%%%%.%.%%%%%%.%%%...%
%.%.....%......%......%.....%.%
%.%%%.%%%%%.%%%%%%%.%%%.%.%%%%%
%.....%........P....%...%.....%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/minimaxClassic.lay
================================================
%%%%%%%%%
%.P G%
% %.%G%%%
%G %%%
%%%%%%%%%
================================================
FILE: Project-1/layouts/oddSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%...%.........%%...%
%.%.%.%%%%%%%%%%.%.%
%..................%
%%%%%%%%.%.%%%%%%%P%
%%%%%%%%....... %
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/openClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%
%.. P .... .... %
%.. ... ... ... ... %
%.. ... ... ... ... %
%.. .... .... G %
%.. ... ... ... ... %
%.. ... ... ... ... %
%.. .... .... o%
%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/openMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% P%
% % %
% % %
% % %
% % %
% % %
% % % %
% % % %
% % % %
% % % %
% % % %
% % % %
% % % %
%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%
% % %
% % %
% % %
% %
% %
% %
%. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/openSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%..................%
%..................%
%........P.........%
%..................%
%..................%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/originalClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%............%%............%
%.%%%%.%%%%%.%%.%%%%%.%%%%.%
%o%%%%.%%%%%.%%.%%%%%.%%%%o%
%.%%%%.%%%%%.%%.%%%%%.%%%%.%
%..........................%
%.%%%%.%%.%%%%%%%%.%%.%%%%.%
%.%%%%.%%.%%%%%%%%.%%.%%%%.%
%......%%....%%....%%......%
%%%%%%.%%%%% %% %%%%%.%%%%%%
%%%%%%.%%%%% %% %%%%%.%%%%%%
%%%%%%.% %.%%%%%%
%%%%%%.% %%%% %%%% %.%%%%%%
% . %G GG G% . %
%%%%%%.% %%%%%%%%%% %.%%%%%%
%%%%%%.% %.%%%%%%
%%%%%%.% %%%%%%%%%% %.%%%%%%
%............%%............%
%.%%%%.%%%%%.%%.%%%%%.%%%%.%
%.%%%%.%%%%%.%%.%%%%%.%%%%.%
%o..%%....... .......%%..o%
%%%.%%.%%.%%%%%%%%.%%.%%.%%%
%%%.%%.%%.%%%%%%%%.%%.%%.%%%
%......%%....%%....%%......%
%.%%%%%%%%%%.%%.%%%%%%%%%%.%
%.............P............%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/smallClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%......%G G%......%
%.%%...%% %%...%%.%
%.%o.%........%.o%.%
%.%%.%.%%%%%%.%.%%.%
%........P.........%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/smallMaze.lay
================================================
%%%%%%%%%%%%%%%%%%%%%%
% %% % % %
% %%%%%% % %%%%%% %
%%%%%% P % %
% % %%%%%% %% %%%%%
% %%%% % % %
% %%% %%% % %
%%%%%%%%%% %%%%%% %
%. %% %
%%%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/smallSafeSearch.lay
================================================
%%%%%%%%%
%.. % G %
%%% %%%%%
% %
%%%%%%% %
% %
% %%%%% %
% % %
%%%%% % %
% %o%
% %%%%%%%
% .%
%%%%%%%.%
%Po .%
%%%%%%%%%
================================================
FILE: Project-1/layouts/smallSearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%. ...P .%
%.%%.%%.%%.%%.%% %.%
% %% %..... %.%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/testClassic.lay
================================================
%%%%%
% . %
%.G.%
% . %
%. .%
% %
% .%
% %
%P .%
%%%%%
================================================
FILE: Project-1/layouts/testMaze.lay
================================================
%%%%%%%%%%
%. P%
%%%%%%%%%%
================================================
FILE: Project-1/layouts/testSearch.lay
================================================
%%%%%
%.P %
%%% %
%. %
%%%%%
================================================
FILE: Project-1/layouts/tinyCorners.lay
================================================
%%%%%%%%
%. .%
% P %
% %%%% %
% % %
% % %%%%
%.% .%
%%%%%%%%
================================================
FILE: Project-1/layouts/tinyMaze.lay
================================================
%%%%%%%
% P%
% %%% %
% % %
%% %%
%. %%%%
%%%%%%%
================================================
FILE: Project-1/layouts/tinySafeSearch.lay
================================================
%%%%%%%%%
% G %...%
%%%%%%% %
%Po %
%.%%.%%.%
%.%%....%
%%%%%%%%%
================================================
FILE: Project-1/layouts/tinySearch.lay
================================================
%%%%%%%%%
%.. ..%
%%%%.%% %
% P %
%.%% %%.%
%.%. .%
%%%%%%%%%
================================================
FILE: Project-1/layouts/trappedClassic.lay
================================================
%%%%%%%%
% P G%
%G%%%%%%
%.... %
%%%%%%%%
================================================
FILE: Project-1/layouts/trickyClassic.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%o...%........%...o%
%.%%.%.%%..%%.%.%%.%
%.%.....%..%.....%.%
%.%.%%.%% %%.%%.%.%
%...... GGGG%.%....%
%.%....%%%%%%.%..%.%
%.%....% oo%.%..%.%
%.%....% %%%%.%..%.%
%.%...........%..%.%
%.%%.%.%%%%%%.%.%%.%
%o...%...P....%...o%
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/layouts/trickySearch.lay
================================================
%%%%%%%%%%%%%%%%%%%%
%. ..% %
%.%%.%%.%%.%%.%% % %
% P % %
%%%%%%%%%%%%%%%%%% %
%..... %
%%%%%%%%%%%%%%%%%%%%
================================================
FILE: Project-1/pacman.py
================================================
# pacman.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"""
Pacman.py holds the logic for the classic pacman game along with the main
code to run a game. This file is divided into three sections:
(i) Your interface to the pacman world:
Pacman is a complex environment. You probably don't want to
read through all of the code we wrote to make the game runs
correctly. This section contains the parts of the code
that you will need to understand in order to complete the
project. There is also some code in game.py that you should
understand.
(ii) The hidden secrets of pacman:
This section contains all of the logic code that the pacman
environment uses to decide who can move where, who dies when
things collide, etc. You shouldn't need to read this section
of code, but you can if you want.
(iii) Framework to start a game:
The final section contains the code for reading the command
you use to set up the game, then starting up a new game, along with
linking in all the external parts (agent functions, graphics).
Check this section out to see all the options available to you.
To play your first game, type 'python pacman.py' from the command line.
The keys are 'a', 's', 'd', and 'w' to move (or arrow keys). Have fun!
"""
from game import GameStateData
from game import Game
from game import Directions
from game import Actions
from util import nearestPoint
from util import manhattanDistance
import util, layout
import sys, types, time, random, os
###################################################
# YOUR INTERFACE TO THE PACMAN WORLD: A GameState #
###################################################
class GameState:
"""
A GameState specifies the full game state, including the food, capsules,
agent configurations and score changes.
GameStates are used by the Game object to capture the actual state of the game and
can be used by agents to reason about the game.
Much of the information in a GameState is stored in a GameStateData object. We
strongly suggest that you access that data via the accessor methods below rather
than referring to the GameStateData object directly.
Note that in classic Pacman, Pacman is always agent 0.
"""
####################################################
# Accessor methods: use these to access state data #
####################################################
# static variable keeps track of which states have had getLegalActions called
explored = set()
def getAndResetExplored():
tmp = GameState.explored.copy()
GameState.explored = set()
return tmp
getAndResetExplored = staticmethod(getAndResetExplored)
def getLegalActions( self, agentIndex=0 ):
"""
Returns the legal actions for the agent specified.
"""
# GameState.explored.add(self)
if self.isWin() or self.isLose(): return []
if agentIndex == 0: # Pacman is moving
return PacmanRules.getLegalActions( self )
else:
return GhostRules.getLegalActions( self, agentIndex )
def generateSuccessor( self, agentIndex, action):
"""
Returns the successor state after the specified agent takes the action.
"""
# Check that successors exist
if self.isWin() or self.isLose(): raise Exception('Can\'t generate a successor of a terminal state.')
# Copy current state
state = GameState(self)
# Let agent's logic deal with its action's effects on the board
if agentIndex == 0: # Pacman is moving
state.data._eaten = [False for i in range(state.getNumAgents())]
PacmanRules.applyAction( state, action )
else: # A ghost is moving
GhostRules.applyAction( state, action, agentIndex )
# Time passes
if agentIndex == 0:
state.data.scoreChange += -TIME_PENALTY # Penalty for waiting around
else:
GhostRules.decrementTimer( state.data.agentStates[agentIndex] )
# Resolve multi-agent effects
GhostRules.checkDeath( state, agentIndex )
# Book keeping
state.data._agentMoved = agentIndex
state.data.score += state.data.scoreChange
GameState.explored.add(self)
GameState.explored.add(state)
return state
def getLegalPacmanActions( self ):
return self.getLegalActions( 0 )
def generatePacmanSuccessor( self, action ):
"""
Generates the successor state after the specified pacman move
"""
return self.generateSuccessor( 0, action )
def getPacmanState( self ):
"""
Returns an AgentState object for pacman (in game.py)
state.pos gives the current position
state.direction gives the travel vector
"""
return self.data.agentStates[0].copy()
def getPacmanPosition( self ):
return self.data.agentStates[0].getPosition()
def getGhostStates( self ):
return self.data.agentStates[1:]
def getGhostState( self, agentIndex ):
if agentIndex == 0 or agentIndex >= self.getNumAgents():
raise Exception("Invalid index passed to getGhostState")
return self.data.agentStates[agentIndex]
def getGhostPosition( self, agentIndex ):
if agentIndex == 0:
raise Exception("Pacman's index passed to getGhostPosition")
return self.data.agentStates[agentIndex].getPosition()
def getGhostPositions(self):
return [s.getPosition() for s in self.getGhostStates()]
def getNumAgents( self ):
return len( self.data.agentStates )
def getScore( self ):
return float(self.data.score)
def getCapsules(self):
"""
Returns a list of positions (x,y) of the remaining capsules.
"""
return self.data.capsules
def getNumFood( self ):
return self.data.food.count()
def getFood(self):
"""
Returns a Grid of boolean food indicator variables.
Grids can be accessed via list notation, so to check
if there is food at (x,y), just call
currentFood = state.getFood()
if currentFood[x][y] == True: ...
"""
return self.data.food
def getWalls(self):
"""
Returns a Grid of boolean wall indicator variables.
Grids can be accessed via list notation, so to check
if there is a wall at (x,y), just call
walls = state.getWalls()
if walls[x][y] == True: ...
"""
return self.data.layout.walls
def hasFood(self, x, y):
return self.data.food[x][y]
def hasWall(self, x, y):
return self.data.layout.walls[x][y]
def isLose( self ):
return self.data._lose
def isWin( self ):
return self.data._win
#############################################
# Helper methods: #
# You shouldn't need to call these directly #
#############################################
def __init__( self, prevState = None ):
"""
Generates a new state by copying information from its predecessor.
"""
if prevState != None: # Initial state
self.data = GameStateData(prevState.data)
else:
self.data = GameStateData()
def deepCopy( self ):
state = GameState( self )
state.data = self.data.deepCopy()
return state
def __eq__( self, other ):
"""
Allows two states to be compared.
"""
return hasattr(other, 'data') and self.data == other.data
def __hash__( self ):
"""
Allows states to be keys of dictionaries.
"""
return hash( self.data )
def __str__( self ):
return str(self.data)
def initialize( self, layout, numGhostAgents=1000 ):
"""
Creates an initial game state from a layout array (see layout.py).
"""
self.data.initialize(layout, numGhostAgents)
############################################################################
# THE HIDDEN SECRETS OF PACMAN #
# #
# You shouldn't need to look through the code in this section of the file. #
############################################################################
SCARED_TIME = 40 # Moves ghosts are scared
COLLISION_TOLERANCE = 0.7 # How close ghosts must be to Pacman to kill
TIME_PENALTY = 1 # Number of points lost each round
class ClassicGameRules:
"""
These game rules manage the control flow of a game, deciding when
and how the game starts and ends.
"""
def __init__(self, timeout=30):
self.timeout = timeout
def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = False, catchExceptions=False):
agents = [pacmanAgent] + ghostAgents[:layout.getNumGhosts()]
initState = GameState()
initState.initialize( layout, len(ghostAgents) )
game = Game(agents, display, self, catchExceptions=catchExceptions)
game.state = initState
self.initialState = initState.deepCopy()
self.quiet = quiet
return game
def process(self, state, game):
"""
Checks to see whether it is time to end the game.
"""
if state.isWin(): self.win(state, game)
if state.isLose(): self.lose(state, game)
def win( self, state, game ):
if not self.quiet: print "Pacman emerges victorious! Score: %d" % state.data.score
game.gameOver = True
def lose( self, state, game ):
if not self.quiet: print "Pacman died! Score: %d" % state.data.score
game.gameOver = True
def getProgress(self, game):
return float(game.state.getNumFood()) / self.initialState.getNumFood()
def agentCrash(self, game, agentIndex):
if agentIndex == 0:
print "Pacman crashed"
else:
print "A ghost crashed"
def getMaxTotalTime(self, agentIndex):
return self.timeout
def getMaxStartupTime(self, agentIndex):
return self.timeout
def getMoveWarningTime(self, agentIndex):
return self.timeout
def getMoveTimeout(self, agentIndex):
return self.timeout
def getMaxTimeWarnings(self, agentIndex):
return 0
class PacmanRules:
"""
These functions govern how pacman interacts with his environment under
the classic game rules.
"""
PACMAN_SPEED=1
def getLegalActions( state ):
"""
Returns a list of possible actions.
"""
return Actions.getPossibleActions( state.getPacmanState().configuration, state.data.layout.walls )
getLegalActions = staticmethod( getLegalActions )
def applyAction( state, action ):
"""
Edits the state to reflect the results of the action.
"""
legal = PacmanRules.getLegalActions( state )
if action not in legal:
raise Exception("Illegal action " + str(action))
pacmanState = state.data.agentStates[0]
# Update Configuration
vector = Actions.directionToVector( action, PacmanRules.PACMAN_SPEED )
pacmanState.configuration = pacmanState.configuration.generateSuccessor( vector )
# Eat
next = pacmanState.configuration.getPosition()
nearest = nearestPoint( next )
if manhattanDistance( nearest, next ) <= 0.5 :
# Remove food
PacmanRules.consume( nearest, state )
applyAction = staticmethod( applyAction )
def consume( position, state ):
x,y = position
# Eat food
if state.data.food[x][y]:
state.data.scoreChange += 10
state.data.food = state.data.food.copy()
state.data.food[x][y] = False
state.data._foodEaten = position
# TODO: cache numFood?
numFood = state.getNumFood()
if numFood == 0 and not state.data._lose:
state.data.scoreChange += 500
state.data._win = True
# Eat capsule
if( position in state.getCapsules() ):
state.data.capsules.remove( position )
state.data._capsuleEaten = position
# Reset all ghosts' scared timers
for index in range( 1, len( state.data.agentStates ) ):
state.data.agentStates[index].scaredTimer = SCARED_TIME
consume = staticmethod( consume )
class GhostRules:
"""
These functions dictate how ghosts interact with their environment.
"""
GHOST_SPEED=1.0
def getLegalActions( state, ghostIndex ):
"""
Ghosts cannot stop, and cannot turn around unless they
reach a dead end, but can turn 90 degrees at intersections.
"""
conf = state.getGhostState( ghostIndex ).configuration
possibleActions = Actions.getPossibleActions( conf, state.data.layout.walls )
reverse = Actions.reverseDirection( conf.direction )
if Directions.STOP in possibleActions:
possibleActions.remove( Directions.STOP )
if reverse in possibleActions and len( possibleActions ) > 1:
possibleActions.remove( reverse )
return possibleActions
getLegalActions = staticmethod( getLegalActions )
def applyAction( state, action, ghostIndex):
legal = GhostRules.getLegalActions( state, ghostIndex )
if action not in legal:
raise Exception("Illegal ghost action " + str(action))
ghostState = state.data.agentStates[ghostIndex]
speed = GhostRules.GHOST_SPEED
if ghostState.scaredTimer > 0: speed /= 2.0
vector = Actions.directionToVector( action, speed )
ghostState.configuration = ghostState.configuration.generateSuccessor( vector )
applyAction = staticmethod( applyAction )
def decrementTimer( ghostState):
timer = ghostState.scaredTimer
if timer == 1:
ghostState.configuration.pos = nearestPoint( ghostState.configuration.pos )
ghostState.scaredTimer = max( 0, timer - 1 )
decrementTimer = staticmethod( decrementTimer )
def checkDeath( state, agentIndex):
pacmanPosition = state.getPacmanPosition()
if agentIndex == 0: # Pacman just moved; Anyone can kill him
for index in range( 1, len( state.data.agentStates ) ):
ghostState = state.data.agentStates[index]
ghostPosition = ghostState.configuration.getPosition()
if GhostRules.canKill( pacmanPosition, ghostPosition ):
GhostRules.collide( state, ghostState, index )
else:
ghostState = state.data.agentStates[agentIndex]
ghostPosition = ghostState.configuration.getPosition()
if GhostRules.canKill( pacmanPosition, ghostPosition ):
GhostRules.collide( state, ghostState, agentIndex )
checkDeath = staticmethod( checkDeath )
def collide( state, ghostState, agentIndex):
if ghostState.scaredTimer > 0:
state.data.scoreChange += 200
GhostRules.placeGhost(state, ghostState)
ghostState.scaredTimer = 0
# Added for first-person
state.data._eaten[agentIndex] = True
else:
if not state.data._win:
state.data.scoreChange -= 500
state.data._lose = True
collide = staticmethod( collide )
def canKill( pacmanPosition, ghostPosition ):
return manhattanDistance( ghostPosition, pacmanPosition ) <= COLLISION_TOLERANCE
canKill = staticmethod( canKill )
def placeGhost(state, ghostState):
ghostState.configuration = ghostState.start
placeGhost = staticmethod( placeGhost )
#############################
# FRAMEWORK TO START A GAME #
#############################
def default(str):
return str + ' [Default: %default]'
def parseAgentArgs(str):
if str == None: return {}
pieces = str.split(',')
opts = {}
for p in pieces:
if '=' in p:
key, val = p.split('=')
else:
key,val = p, 1
opts[key] = val
return opts
def readCommand( argv ):
"""
Processes the command used to run pacman from the command line.
"""
from optparse import OptionParser
usageStr = """
USAGE: python pacman.py <options>
EXAMPLES: (1) python pacman.py
- starts an interactive game
(2) python pacman.py --layout smallClassic --zoom 2
OR python pacman.py -l smallClassic -z 2
- starts an interactive game on a smaller board, zoomed in
"""
parser = OptionParser(usageStr)
parser.add_option('-n', '--numGames', dest='numGames', type='int',
help=default('the number of GAMES to play'), metavar='GAMES', default=1)
parser.add_option('-l', '--layout', dest='layout',
help=default('the LAYOUT_FILE from which to load the map layout'),
metavar='LAYOUT_FILE', default='mediumClassic')
parser.add_option('-p', '--pacman', dest='pacman',
help=default('the agent TYPE in the pacmanAgents module to use'),
metavar='TYPE', default='KeyboardAgent')
parser.add_option('-t', '--textGraphics', action='store_true', dest='textGraphics',
help='Display output as text only', default=False)
parser.add_option('-q', '--quietTextGraphics', action='store_true', dest='quietGraphics',
help='Generate minimal output and no graphics', default=False)
parser.add_option('-g', '--ghosts', dest='ghost',
help=default('the ghost agent TYPE in the ghostAgents module to use'),
metavar = 'TYPE', default='RandomGhost')
parser.add_option('-k', '--numghosts', type='int', dest='numGhosts',
help=default('The maximum number of ghosts to use'), default=4)
parser.add_option('-z', '--zoom', type='float', dest='zoom',
help=default('Zoom the size of the graphics window'), default=1.0)
parser.add_option('-f', '--fixRandomSeed', action='store_true', dest='fixRandomSeed',
help='Fixes the random seed to always play the same game', default=False)
parser.add_option('-r', '--recordActions', action='store_true', dest='record',
help='Writes game histories to a file (named by the time they were played)', default=False)
parser.add_option('--replay', dest='gameToReplay',
help='A recorded game file (pickle) to replay', default=None)
parser.add_option('-a','--agentArgs',dest='agentArgs',
help='Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"')
parser.add_option('-x', '--numTraining', dest='numTraining', type='int',
help=default('How many episodes are training (suppresses output)'), default=0)
parser.add_option('--frameTime', dest='frameTime', type='float',
help=default('Time to delay between frames; <0 means keyboard'), default=0.1)
parser.add_option('-c', '--catchExceptions', action='store_true', dest='catchExceptions',
help='Turns on exception handling and timeouts during games', default=False)
parser.add_option('--timeout', dest='timeout', type='int',
help=default('Maximum length of time an agent can spend computing in a single game'), default=30)
options, otherjunk = parser.parse_args(argv)
if len(otherjunk) != 0:
raise Exception('Command line input not understood: ' + str(otherjunk))
args = dict()
# Fix the random seed
if options.fixRandomSeed: random.seed('cs188')
# Choose a layout
args['layout'] = layout.getLayout( options.layout )
if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found")
# Choose a Pacman agent
noKeyboard = options.gameToReplay == None and (options.textGraphics or options.quietGraphics)
pacmanType = loadAgent(options.pacman, noKeyboard)
agentOpts = parseAgentArgs(options.agentArgs)
if options.numTraining > 0:
args['numTraining'] = options.numTraining
if 'numTraining' not in agentOpts: agentOpts['numTraining'] = options.numTraining
pacman = pacmanType(**agentOpts) # Instantiate Pacman with agentArgs
args['pacman'] = pacman
# Don't display training games
if 'numTrain' in agentOpts:
options.numQuiet = int(agentOpts['numTrain'])
options.numIgnore = int(agentOpts['numTrain'])
# Choose a ghost agent
ghostType = loadAgent(options.ghost, noKeyboard)
args['ghosts'] = [ghostType( i+1 ) for i in range( options.numGhosts )]
# Choose a display format
if options.quietGraphics:
import textDisplay
args['display'] = textDisplay.NullGraphics()
elif options.textGraphics:
import textDisplay
textDisplay.SLEEP_TIME = options.frameTime
args['display'] = textDisplay.PacmanGraphics()
else:
import graphicsDisplay
args['display'] = graphicsDisplay.PacmanGraphics(options.zoom, frameTime = options.frameTime)
args['numGames'] = options.numGames
args['record'] = options.record
args['catchExceptions'] = options.catchExceptions
args['timeout'] = options.timeout
# Special case: recorded games don't use the runGames method or args structure
if options.gameToReplay != None:
print 'Replaying recorded game %s.' % options.gameToReplay
import cPickle
f = open(options.gameToReplay)
try: recorded = cPickle.load(f)
finally: f.close()
recorded['display'] = args['display']
replayGame(**recorded)
sys.exit(0)
return args
def loadAgent(pacman, nographics):
# Looks through all pythonPath Directories for the right module,
pythonPathStr = os.path.expandvars("$PYTHONPATH")
if pythonPathStr.find(';') == -1:
pythonPathDirs = pythonPathStr.split(':')
else:
pythonPathDirs = pythonPathStr.split(';')
pythonPathDirs.append('.')
for moduleDir in pythonPathDirs:
if not os.path.isdir(moduleDir): continue
moduleNames = [f for f in os.listdir(moduleDir) if f.endswith('gents.py')]
for modulename in moduleNames:
try:
module = __import__(modulename[:-3])
except ImportError:
continue
if pacman in dir(module):
if nographics and modulename == 'keyboardAgents.py':
raise Exception('Using the keyboard requires graphics (not text display)')
return getattr(module, pacman)
raise Exception('The agent ' + pacman + ' is not specified in any *Agents.py.')
def replayGame( layout, actions, display ):
import pacmanAgents, ghostAgents
rules = ClassicGameRules()
agents = [pacmanAgents.GreedyAgent()] + [ghostAgents.RandomGhost(i+1) for i in range(layout.getNumGhosts())]
game = rules.newGame( layout, agents[0], agents[1:], display )
state = game.state
display.initialize(state.data)
for action in actions:
# Execute the action
state = state.generateSuccessor( *action )
# Change the display
display.update( state.data )
# Allow for game specific conditions (winning, losing, etc.)
rules.process(state, game)
display.finish()
def runGames( layout, pacman, ghosts, display, numGames, record, numTraining = 0, catchExceptions=False, timeout=30 ):
import __main__
__main__.__dict__['_display'] = display
rules = ClassicGameRules(timeout)
games = []
for i in range( numGames ):
beQuiet = i < numTraining
if beQuiet:
# Suppress output and graphics
import textDisplay
gameDisplay = textDisplay.NullGraphics()
rules.quiet = True
else:
gameDisplay = display
rules.quiet = False
game = rules.newGame( layout, pacman, ghosts, gameDisplay, beQuiet, catchExceptions)
game.run()
if not beQuiet: games.append(game)
if record:
import time, cPickle
fname = ('recorded-game-%d' % (i + 1)) + '-'.join([str(t) for t in time.localtime()[1:6]])
f = file(fname, 'w')
components = {'layout': layout, 'actions': game.moveHistory}
cPickle.dump(components, f)
f.close()
if (numGames-numTraining) > 0:
scores = [game.state.getScore() for game in games]
wins = [game.state.isWin() for game in games]
winRate = wins.count(True)/ float(len(wins))
print 'Average Score:', sum(scores) / float(len(scores))
print 'Scores: ', ', '.join([str(score) for score in scores])
print 'Win Rate: %d/%d (%.2f)' % (wins.count(True), len(wins), winRate)
print 'Record: ', ', '.join([ ['Loss', 'Win'][int(w)] for w in wins])
return games
if __name__ == '__main__':
"""
The main function called when pacman.py is run
from the command line:
> python pacman.py
See the usage string for more details.
> python pacman.py --help
"""
args = readCommand( sys.argv[1:] ) # Get game components based on input
runGames( **args )
# import cProfile
# cProfile.run("runGames( **args )")
pass
================================================
FILE: Project-1/pacmanAgents.py
================================================
# pacmanAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from pacman import Directions
from game import Agent
import random
import game
import util
class LeftTurnAgent(game.Agent):
"An agent that turns left at every opportunity"
def getAction(self, state):
legal = state.getLegalPacmanActions()
current = state.getPacmanState().configuration.direction
if current == Directions.STOP: current = Directions.NORTH
left = Directions.LEFT[current]
if left in legal: return left
if current in legal: return current
if Directions.RIGHT[current] in legal: return Directions.RIGHT[current]
if Directions.LEFT[left] in legal: return Directions.LEFT[left]
return Directions.STOP
class GreedyAgent(Agent):
def __init__(self, evalFn="scoreEvaluation"):
self.evaluationFunction = util.lookup(evalFn, globals())
assert self.evaluationFunction != None
def getAction(self, state):
# Generate candidate actions
legal = state.getLegalPacmanActions()
if Directions.STOP in legal: legal.remove(Directions.STOP)
successors = [(state.generateSuccessor(0, action), action) for action in legal]
scored = [(self.evaluationFunction(state), action) for state, action in successors]
bestScore = max(scored)[0]
bestActions = [pair[1] for pair in scored if pair[0] == bestScore]
return random.choice(bestActions)
def scoreEvaluation(state):
return state.getScore()
================================================
FILE: Project-1/projectParams.py
================================================
# projectParams.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
STUDENT_CODE_DEFAULT = 'searchAgents.py,search.py'
PROJECT_TEST_CLASSES = 'searchTestClasses.py'
PROJECT_NAME = 'Project 1: Search'
BONUS_PIC = False
================================================
FILE: Project-1/search.py
================================================
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""
import util
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
You do not need to change anything in this class, ever.
"""
def getStartState(self):
"""
Returns the start state for the search problem.
"""
util.raiseNotDefined()
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state.
"""
util.raiseNotDefined()
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost' is
the incremental cost of expanding to that successor.
"""
util.raiseNotDefined()
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions.
The sequence must be composed of legal moves.
"""
util.raiseNotDefined()
class Path(object):
def __init__(self, locations, directions, cost):
self.locations = locations
self.directions = directions
self.cost = cost
def tinyMazeSearch(problem):
"""
Returns a sequence of moves that solves tinyMaze. For any other maze, the
sequence of moves will be incorrect, so only use this for tinyMaze.
"""
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
return [s, s, w, s, w, w, s, w]
def depthFirstSearch(problem):
""" Search the deepest nodes in the search tree first."""
path = Path([problem.getStartState()],[],0)
if problem.isGoalState(problem.getStartState()):
return path.directions
stack = util.Stack()
stack.push(path)
while not stack.isEmpty():
currentPath = stack.pop()
currentLocation = currentPath.locations[-1]
if problem.isGoalState(currentLocation):
return currentPath.directions
else:
nextSteps = problem.getSuccessors(currentLocation)
for nextStep in nextSteps:
nextLocation = nextStep[0]
nextDirection = nextStep[1]
nextCost = nextStep[2]
if nextLocation not in currentPath.locations:
nextLocations = currentPath.locations[:]
nextLocations.append(nextLocation)
nextDirections = currentPath.directions[:]
nextDirections.append(nextDirection)
nextCosts = currentPath.cost + nextCost
nextPath = Path(nextLocations, nextDirections, nextCosts)
stack.push(nextPath)
return []
def breadthFirstSearch(problem):
"""Search the shallowest nodes in the search tree first."""
path = Path([problem.getStartState()],[],0)
if problem.isGoalState(problem.getStartState()):
return path.directions
queue = util.Queue()
queue.push(path)
visited = [problem.getStartState()]
while not queue.isEmpty():
currentPath = queue.pop()
currentLocation = currentPath.locations[-1]
if problem.isGoalState(currentLocation):
return currentPath.directions
else:
nextSteps = problem.getSuccessors(currentLocation)
for nextStep in nextSteps:
nextLocation = nextStep[0]
nextDirection = nextStep[1]
nextCost = nextStep[2]
if (nextLocation not in currentPath.locations) and (nextLocation not in visited):
if not problem.isGoalState(nextLocation):
visited.append(nextLocation)
nextLocations = currentPath.locations[:]
nextLocations.append(nextLocation)
nextDirections = currentPath.directions[:]
nextDirections.append(nextDirection)
nextCosts = currentPath.cost + nextCost
nextPath = Path(nextLocations, nextDirections, nextCosts)
queue.push(nextPath)
return []
def uniformCostSearch(problem):
"""Search the node of least total cost first."""
path = Path([problem.getStartState()],[],0)
if problem.isGoalState(problem.getStartState()):
return path.directions
queue = util.PriorityQueue()
queue.push(path, 0)
visited = [problem.getStartState()]
while not queue.isEmpty():
currentPath = queue.pop()
currentLocation = currentPath.locations[-1]
if problem.isGoalState(currentLocation):
return currentPath.directions
else:
nextSteps = problem.getSuccessors(currentLocation)
for nextStep in nextSteps:
nextLocation = nextStep[0]
nextDirection = nextStep[1]
nextCost = nextStep[2]
if (nextLocation not in currentPath.locations) and (nextLocation not in visited):
if not problem.isGoalState(nextLocation):
visited.append(nextLocation)
nextLocations = currentPath.locations[:]
nextLocations.append(nextLocation)
nextDirections = currentPath.directions[:]
nextDirections.append(nextDirection)
nextCosts = currentPath.cost + nextCost
nextPath = Path(nextLocations, nextDirections, nextCosts)
queue.push(nextPath, nextCosts)
return []
def nullHeuristic(state, problem=None):
"""
A heuristic function estimates the cost from the current state to the nearest
goal in the provided SearchProblem. This heuristic is trivial.
"""
return 0
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
path = Path([problem.getStartState()],[],0)
if problem.isGoalState(problem.getStartState()):
return path.directions
queue = util.PriorityQueue()
queue.push(path, 0)
visited = [problem.getStartState()]
while not queue.isEmpty():
currentPath = queue.pop()
currentLocation = currentPath.locations[-1]
if problem.isGoalState(currentLocation):
return currentPath.directions
else:
nextSteps = problem.getSuccessors(currentLocation)
for nextStep in nextSteps:
nextLocation = nextStep[0]
nextDirection = nextStep[1]
nextCost = nextStep[2]
if (nextLocation not in currentPath.locations) and (nextLocation not in visited):
if not problem.isGoalState(nextLocation):
visited.append(nextLocation)
nextLocations = currentPath.locations[:]
nextLocations.append(nextLocation)
nextDirections = currentPath.directions[:]
nextDirections.append(nextDirection)
nextCosts = currentPath.cost + nextCost
nextHeuristic = heuristic(nextLocation, problem)
nextPath = Path(nextLocations, nextDirections, nextCosts)
queue.push(nextPath, nextCosts + nextHeuristic)
return []
# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch
================================================
FILE: Project-1/searchAgents.py
================================================
# searchAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"""
This file contains all of the agents that can be selected to control Pacman. To
select an agent, use the '-p' option when running pacman.py. Arguments can be
passed to your agent using '-a'. For example, to load a SearchAgent that uses
depth first search (dfs), run the following command:
> python pacman.py -p SearchAgent -a fn=depthFirstSearch
Commands to invoke other search strategies can be found in the project
description.
Please only change the parts of the file you are asked to. Look for the lines
that say
"*** YOUR CODE HERE ***"
The parts you fill in start about 3/4 of the way down. Follow the project
description for details.
Good luck and happy searching!
"""
from game import Directions
from game import Agent
from game import Actions
import util
import time
import search
class GoWestAgent(Agent):
"An agent that goes West until it can't."
def getAction(self, state):
"The agent receives a GameState (defined in pacman.py)."
if Directions.WEST in state.getLegalPacmanActions():
return Directions.WEST
else:
return Directions.STOP
#######################################################
# This portion is written for you, but will only work #
# after you fill in parts of search.py #
#######################################################
class SearchAgent(Agent):
"""
This very general search agent finds a path using a supplied search
algorithm for a supplied search problem, then returns actions to follow that
path.
As a default, this agent runs DFS on a PositionSearchProblem to find
location (1,1)
Options for fn include:
depthFirstSearch or dfs
breadthFirstSearch or bfs
Note: You should NOT change any code in SearchAgent
"""
def __init__(self, fn='depthFirstSearch', prob='PositionSearchProblem', heuristic='nullHeuristic'):
# Warning: some advanced Python magic is employed below to find the right functions and problems
# Get the search function from the name and heuristic
if fn not in dir(search):
raise AttributeError, fn + ' is not a search function in search.py.'
func = getattr(search, fn)
if 'heuristic' not in func.func_code.co_varnames:
print('[SearchAgent] using function ' + fn)
self.searchFunction = func
else:
if heuristic in globals().keys():
heur = globals()[heuristic]
elif heuristic in dir(search):
heur = getattr(search, heuristic)
else:
raise AttributeError, heuristic + ' is not a function in searchAgents.py or search.py.'
print('[SearchAgent] using function %s and heuristic %s' % (fn, heuristic))
# Note: this bit of Python trickery combines the search algorithm and the heuristic
self.searchFunction = lambda x: func(x, heuristic=heur)
# Get the search problem type from the name
if prob not in globals().keys() or not prob.endswith('Problem'):
raise AttributeError, prob + ' is not a search problem type in SearchAgents.py.'
self.searchType = globals()[prob]
print('[SearchAgent] using problem type ' + prob)
def registerInitialState(self, state):
"""
This is the first time that the agent sees the layout of the game
board. Here, we choose a path to the goal. In this phase, the agent
should compute the path to the goal and store it in a local variable.
All of the work is done in this method!
state: a GameState object (pacman.py)
"""
if self.searchFunction == None: raise Exception, "No search function provided for SearchAgent"
starttime = time.time()
problem = self.searchType(state) # Makes a new search problem
self.actions = self.searchFunction(problem) # Find a path
totalCost = problem.getCostOfActions(self.actions)
print('Path found with total cost of %d in %.1f seconds' % (totalCost, time.time() - starttime))
if '_expanded' in dir(problem): print('Search nodes expanded: %d' % problem._expanded)
def getAction(self, state):
"""
Returns the next action in the path chosen earlier (in
registerInitialState). Return Directions.STOP if there is no further
action to take.
state: a GameState object (pacman.py)
"""
if 'actionIndex' not in dir(self): self.actionIndex = 0
i = self.actionIndex
self.actionIndex += 1
if i < len(self.actions):
return self.actions[i]
else:
return Directions.STOP
class PositionSearchProblem(search.SearchProblem):
"""
A search problem defines the state space, start state, goal test, successor
function and cost function. This search problem can be used to find paths
to a particular point on the pacman board.
The state space consists of (x,y) positions in a pacman game.
Note: this search problem is fully specified; you should NOT change it.
"""
def __init__(self, gameState, costFn = lambda x: 1, goal=(1,1), start=None, warn=True, visualize=True):
"""
Stores the start and goal.
gameState: A GameState object (pacman.py)
costFn: A function from a search state (tuple) to a non-negative number
goal: A position in the gameState
"""
self.walls = gameState.getWalls()
self.startState = gameState.getPacmanPosition()
if start != None: self.startState = start
self.goal = goal
self.costFn = costFn
self.visualize = visualize
if warn and (gameState.getNumFood() != 1 or not gameState.hasFood(*goal)):
print 'Warning: this does not look like a regular search maze'
# For display purposes
self._visited, self._visitedlist, self._expanded = {}, [], 0 # DO NOT CHANGE
def getStartState(self):
return self.startState
def isGoalState(self, state):
isGoal = state == self.goal
# For display purposes only
if isGoal and self.visualize:
self._visitedlist.append(state)
import __main__
if '_display' in dir(__main__):
if 'drawExpandedCells' in dir(__main__._display): #@UndefinedVariable
__main__._display.drawExpandedCells(self._visitedlist) #@UndefinedVariable
return isGoal
def getSuccessors(self, state):
"""
Returns successor states, the actions they require, and a cost of 1.
As noted in search.py:
For a given state, this should return a list of triples,
(successor, action, stepCost), where 'successor' is a
successor to the current state, 'action' is the action
required to get there, and 'stepCost' is the incremental
cost of expanding to that successor
"""
successors = []
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextState = (nextx, nexty)
cost = self.costFn(nextState)
successors.append( ( nextState, action, cost) )
# Bookkeeping for display purposes
self._expanded += 1 # DO NOT CHANGE
if state not in self._visited:
self._visited[state] = True
self._visitedlist.append(state)
return successors
def getCostOfActions(self, actions):
"""
Returns the cost of a particular sequence of actions. If those actions
include an illegal move, return 999999.
"""
if actions == None: return 999999
x,y= self.getStartState()
cost = 0
for action in actions:
# Check figure out the next state and see whether its' legal
dx, dy = Actions.directionToVector(action)
x, y = int(x + dx), int(y + dy)
if self.walls[x][y]: return 999999
cost += self.costFn((x,y))
return cost
class StayEastSearchAgent(SearchAgent):
"""
An agent for position search with a cost function that penalizes being in
positions on the West side of the board.
The cost function for stepping into a position (x,y) is 1/2^x.
"""
def __init__(self):
self.searchFunction = search.uniformCostSearch
costFn = lambda pos: .5 ** pos[0]
self.searchType = lambda state: PositionSearchProblem(state, costFn, (1, 1), None, False)
class StayWestSearchAgent(SearchAgent):
"""
An agent for position search with a cost function that penalizes being in
positions on the East side of the board.
The cost function for stepping into a position (x,y) is 2^x.
"""
def __init__(self):
self.searchFunction = search.uniformCostSearch
costFn = lambda pos: 2 ** pos[0]
self.searchType = lambda state: PositionSearchProblem(state, costFn)
def manhattanHeuristic(position, problem, info={}):
"The Manhattan distance heuristic for a PositionSearchProblem"
xy1 = position
xy2 = problem.goal
return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])
def euclideanHeuristic(position, problem, info={}):
"The Euclidean distance heuristic for a PositionSearchProblem"
xy1 = position
xy2 = problem.goal
return ( (xy1[0] - xy2[0]) ** 2 + (xy1[1] - xy2[1]) ** 2 ) ** 0.5
#####################################################
# This portion is incomplete. Time to write code! #
#####################################################
class CornersProblem(search.SearchProblem):
"""
This search problem finds paths through all four corners of a layout.
You must select a suitable state space and successor function
"""
def __init__(self, startingGameState):
"""
Stores the walls, pacman's starting position and corners.
"""
self.walls = startingGameState.getWalls()
self.startingPosition = startingGameState.getPacmanPosition()
top, right = self.walls.height-2, self.walls.width-2
self.corners = ((1,1), (1,top), (right, 1), (right, top))
for corner in self.corners:
if not startingGameState.hasFood(*corner):
print 'Warning: no food in corner ' + str(corner)
self._expanded = 0 # DO NOT CHANGE; Number of search nodes expanded
# Please add any code here which you would like to use
# in initializing the problem
def getStartState(self):
"""
Returns the start state (in your state space, not the full Pacman state
space)
"""
return self.startingPosition, False, False, False, False
def isGoalState(self, state):
"""
Returns whether this search state is a goal state of the problem.
"""
location, corner1, corner2, corner3, corner4 = state
return corner1 and corner2 and corner3 and corner4
def getSuccessors(self, state):
"""
Returns successor states, the actions they require, and a cost of 1.
As noted in search.py:
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost'
is the incremental cost of expanding to that successor
"""
successors = []
currentPosition, corner1, corner2, corner3, corner4 = state
x,y = currentPosition
top, right = self.walls.height-2, self.walls.width-2
for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
dx, dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextPosition = (nextx, nexty)
nextState = (nextPosition, True if nextPosition == (1,1) else corner1, True if nextPosition == (1,top) else corner2, True if nextPosition == (right, 1) else corner3, True if nextPosition == (right, top) else corner4)
successors.append((nextState, action, 1))
self._expanded += 1 # DO NOT CHANGE
return successors
def getCostOfActions(self, actions):
"""
Returns the cost of a particular sequence of actions. If those actions
include an illegal move, return 999999. This is implemented for you.
"""
if actions == None: return 999999
x,y= self.startingPosition
for action in actions:
dx, dy = Actions.directionToVector(action)
x, y = int(x + dx), int(y + dy)
if self.walls[x][y]: return 999999
return len(actions)
def cornersHeuristic(state, problem):
"""
A heuristic for the CornersProblem that you defined.
state: The current search state
(a data structure you chose in your search problem)
problem: The CornersProblem instance for this layout.
This function should always return a number that is a lower bound on the
shortest path from the state to a goal of the problem; i.e. it should be
admissible (as well as consistent).
"""
corners = problem.corners # These are the corner coordinates
walls = problem.walls # These are the walls of the maze, as a Grid (game.py)
cornerPos1, cornerPos2, cornerPos3, cornerPos4 = corners
xPos1, yPos1 = cornerPos1
xPos2, yPos2 = cornerPos2
xPos3, yPos3 = cornerPos3
xPos4, yPos4 = cornerPos4
location, corner1, corner2, corner3, corner4 = state
x, y = location
top, right = walls.height-2, walls.width-2
heuristic = 0
diff1 = abs(xPos1-x)+abs(yPos1-y) if not corner1 else 0
diff2 = abs(xPos2-x)+abs(yPos2-y) if not corner2 else 0
diff3 = abs(xPos3-x)+abs(yPos3-y) if not corner3 else 0
diff4 = abs(xPos4-x)+abs(yPos4-y) if not corner4 else 0
return max([diff1, diff2, diff3, diff4])
class AStarCornersAgent(SearchAgent):
"A SearchAgent for FoodSearchProblem using A* and your foodHeuristic"
def __init__(self):
self.searchFunction = lambda prob: search.aStarSearch(prob, cornersHeuristic)
self.searchType = CornersProblem
class FoodSearchProblem:
"""
A search problem associated with finding the a path that collects all of the
food (dots) in a Pacman game.
A search state in this problem is a tuple ( pacmanPosition, foodGrid ) where
pacmanPosition: a tuple (x,y) of integers specifying Pacman's position
foodGrid: a Grid (see game.py) of either True or False, specifying remaining food
"""
def __init__(self, startingGameState):
self.start = (startingGameState.getPacmanPosition(), startingGameState.getFood())
self.walls = startingGameState.getWalls()
self.startingGameState = startingGameState
self._expanded = 0 # DO NOT CHANGE
self.heuristicInfo = {} # A dictionary for the heuristic to store information
def getStartState(self):
return self.start
def isGoalState(self, state):
return state[1].count() == 0
def getSuccessors(self, state):
"Returns successor states, the actions they require, and a cost of 1."
successors = []
self._expanded += 1 # DO NOT CHANGE
for direction in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state[0]
dx, dy = Actions.directionToVector(direction)
nextx, nexty = int(x + dx), int(y + dy)
if not self.walls[nextx][nexty]:
nextFood = state[1].copy()
nextFood[nextx][nexty] = False
successors.append( ( ((nextx, nexty), nextFood), direction, 1) )
return successors
def getCostOfActions(self, actions):
"""Returns the cost of a particular sequence of actions. If those actions
include an illegal move, return 999999"""
x,y= self.getStartState()[0]
cost = 0
for action in actions:
# figure out the next state and see whether it's legal
dx, dy = Actions.directionToVector(action)
x, y = int(x + dx), int(y + dy)
if self.walls[x][y]:
return 999999
cost += 1
return cost
class AStarFoodSearchAgent(SearchAgent):
"A SearchAgent for FoodSearchProblem using A* and your foodHeuristic"
def __init__(self):
self.searchFunction = lambda prob: search.aStarSearch(prob, foodHeuristic)
self.searchType = FoodSearchProblem
def foodHeuristic(state, problem):
"""
Your heuristic for the FoodSearchProblem goes here.
This heuristic must be consistent to ensure correctness. First, try to come
up with an admissible heuristic; almost all admissible heuristics will be
consistent as well.
If using A* ever finds a solution that is worse uniform cost search finds,
your heuristic is *not* consistent, and probably not admissible! On the
other hand, inadmissible or inconsistent heuristics may find optimal
solutions, so be careful.
The state is a tuple ( pacmanPosition, foodGrid ) where foodGrid is a Grid
(see game.py) of either True or False. You can call foodGrid.asList() to get
a list of food coordinates instead.
If you want access to info like walls, capsules, etc., you can query the
problem. For example, problem.walls gives you a Grid of where the walls
are.
If you want to *store* information to be reused in other calls to the
heuristic, there is a dictionary called problem.heuristicInfo that you can
use. For example, if you only want to count the walls once and store that
value, try: problem.heuristicInfo['wallCount'] = problem.walls.count()
Subsequent calls to this heuristic can access
problem.heuristicInfo['wallCount']
"""
position, foodGrid = state
x, y = position
foodList = list(foodGrid.asList())
maxX = 0
maxY = 0
minX = 0
minY = 0
for item in foodList:
foodX, foodY = item
xDistance = foodX - x
yDistance = foodY - y
if xDistance > maxX:
maxX = xDistance
elif xDistance < minX:
minX = xDistance
if yDistance > maxY:
maxY = yDistance
elif yDistance < minY:
minY = yDistance
return maxX - minX + maxY - minY
class ClosestDotSearchAgent(SearchAgent):
"Search for all food using a sequence of searches"
def registerInitialState(self, state):
self.actions = []
currentState = state
while(currentState.getFood().count() > 0):
nextPathSegment = self.findPathToClosestDot(currentState) # The missing piece
self.actions += nextPathSegment
for action in nextPathSegment:
legal = currentState.getLegalActions()
if action not in legal:
t = (str(action), str(currentState))
raise Exception, 'findPathToClosestDot returned an illegal move: %s!\n%s' % t
currentState = currentState.generateSuccessor(0, action)
self.actionIndex = 0
print 'Path found with cost %d.' % len(self.actions)
def findPathToClosestDot(self, gameState):
"""
Returns a path (a list of actions) to the closest dot, starting from
gameState.
"""
# Here are some useful elements of the startState
startPosition = gameState.getPacmanPosition()
food = gameState.getFood()
walls = gameState.getWalls()
problem = AnyFoodSearchProblem(gameState)
return search.breadthFirstSearch(problem)
class AnyFoodSearchProblem(PositionSearchProblem):
"""
A search problem for finding a path to any food.
This search problem is just like the PositionSearchProblem, but has a
different goal test, which you need to fill in below. The state space and
successor function do not need to be changed.
The class definition above, AnyFoodSearchProblem(PositionSearchProblem),
inherits the methods of the PositionSearchProblem.
You can use this search problem to help you fill in the findPathToClosestDot
method.
"""
def __init__(self, gameState):
"Stores information from the gameState. You don't need to change this."
# Store the food for later reference
self.food = gameState.getFood()
# Store info for the PositionSearchProblem (no need to change this)
self.walls = gameState.getWalls()
self.startState = gameState.getPacmanPosition()
self.costFn = lambda x: 1
self._visited, self._visitedlist, self._expanded = {}, [], 0 # DO NOT CHANGE
def isGoalState(self, state):
"""
The state is Pacman's position. Fill this in with a goal test that will
complete the problem definition.
"""
return state in list(self.food.asList())
def mazeDistance(point1, point2, gameState):
"""
Returns the maze distance between any two points, using the search functions
you have already built. The gameState can be any game state -- Pacman's
position in that state is ignored.
Example usage: mazeDistance( (2,4), (5,6), gameState)
This might be a useful helper function for your ApproximateSearchAgent.
"""
x1, y1 = point1
x2, y2 = point2
walls = gameState.getWalls()
assert not walls[x1][y1], 'point1 is a wall: ' + str(point1)
assert not walls[x2][y2], 'point2 is a wall: ' + str(point2)
prob = PositionSearchProblem(gameState, start=point1, goal=point2, warn=False, visualize=False)
return len(search.bfs(prob))
================================================
FILE: Project-1/searchTestClasses.py
================================================
# searchTestClasses.py
# --------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
import re
import testClasses
import textwrap
# import project specific code
import layout
import pacman
from search import SearchProblem
# helper function for printing solutions in solution files
def wrap_solution(solution):
if type(solution) == type([]):
return '\n'.join(textwrap.wrap(' '.join(solution)))
else:
return str(solution)
def followAction(state, action, problem):
for successor1, action1, cost1 in problem.getSuccessors(state):
if action == action1: return successor1
return None
def followPath(path, problem):
state = problem.getStartState()
states = [state]
for action in path:
state = followAction(state, action, problem)
states.append(state)
return states
def checkSolution(problem, path):
state = problem.getStartState()
for action in path:
state = followAction(state, action, problem)
return problem.isGoalState(state)
# Search problem on a plain graph
class GraphSearch(SearchProblem):
# Read in the state graph; define start/end states, edges and costs
def __init__(self, graph_text):
self.expanded_states = []
lines = graph_text.split('\n')
r = re.match('start_state:(.*)', lines[0])
if r == None:
print "Broken graph:"
print '"""%s"""' % graph_text
raise Exception("GraphSearch graph specification start_state not found or incorrect on line:" + l)
self.start_state = r.group(1).strip()
r = re.match('goal_states:(.*)', lines[1])
if r == None:
print "Broken graph:"
print '"""%s"""' % graph_text
raise Exception("GraphSearch graph specification goal_states not found or incorrect on line:" + l)
goals = r.group(1).split()
self.goals = map(str.strip, goals)
self.successors = {}
all_states = set()
self.orderedSuccessorTuples = []
for l in lines[2:]:
if len(l.split()) == 3:
start, action, next_state = l.split()
cost = 1
elif len(l.split()) == 4:
start, action, next_state, cost = l.split()
else:
print "Broken graph:"
print '"""%s"""' % graph_text
raise Exception("Invalid line in GraphSearch graph specification on line:" + l)
cost = float(cost)
self.orderedSuccessorTuples.append((start, action, next_state, cost))
all_states.add(start)
all_states.add(next_state)
if start not in self.successors:
self.successors[start] = []
self.successors[start].append((next_state, action, cost))
for s in all_states:
if s not in self.successors:
self.successors[s] = []
# Get start state
def getStartState(self):
return self.start_state
# Check if a state is a goal state
def isGoalState(self, state):
return state in self.goals
# Get all successors of a state
def getSuccessors(self, state):
self.expanded_states.append(state)
return list(self.successors[state])
# Calculate total cost of a sequence of actions
def getCostOfActions(self, actions):
total_cost = 0
state = self.start_state
for a in actions:
successors = self.successors[state]
match = False
for (next_state, action, cost) in successors:
if a == action:
state = next_state
total_cost += cost
match = True
if not match:
print 'invalid action sequence'
sys.exit(1)
return total_cost
# Return a list of all states on which 'getSuccessors' was called
def getExpandedStates(self):
return self.expanded_states
def __str__(self):
print self.successors
edges = ["%s %s %s %s" % t for t in self.orderedSuccessorTuples]
return \
"""start_state: %s
goal_states: %s
%s""" % (self.start_state, " ".join(self.goals), "\n".join(edges))
def parseHeuristic(heuristicText):
heuristic = {}
for line in heuristicText.split('\n'):
tokens = line.split()
if len(tokens) != 2:
print "Broken heuristic:"
print '"""%s"""' % graph_text
raise Exception("GraphSearch heuristic specification broken:" + l)
state, h = tokens
heuristic[state] = float(h)
def graphHeuristic(state, problem=None):
if state in heuristic:
return heuristic[state]
else:
pp = pprint.PrettyPrinter(indent=4)
print "Heuristic:"
pp.pprint(heuristic)
raise Exception("Graph heuristic called with invalid state: " + str(state))
return graphHeuristic
class GraphSearchTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(GraphSearchTest, self).__init__(question, testDict)
self.graph_text = testDict['graph']
self.alg = testDict['algorithm']
self.diagram = testDict['diagram']
self.exactExpansionOrder = testDict.get('exactExpansionOrder', 'True').lower() == "true"
if 'heuristic' in testDict:
self.heuristic = parseHeuristic(testDict['heuristic'])
else:
self.heuristic = None
# Note that the return type of this function is a tripple:
# (solution, expanded states, error message)
def getSolInfo(self, search):
alg = getattr(search, self.alg)
problem = GraphSearch(self.graph_text)
if self.heuristic != None:
solution = alg(problem, self.heuristic)
else:
solution = alg(problem)
if type(solution) != type([]):
return None, None, 'The result of %s must be a list. (Instead, it is %s)' % (self.alg, type(solution))
return solution, problem.getExpandedStates(), None
# Run student code. If an error message is returned, print error and return false.
# If a good solution is returned, printn the solution and return true; otherwise,
# print both the correct and student's solution and return false.
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
gold_solution = [str.split(solutionDict['solution']), str.split(solutionDict['rev_solution'])]
gold_expanded_states = [str.split(solutionDict['expanded_states']), str.split(solutionDict['rev_expanded_states'])]
solution, expanded_states, error = self.getSolInfo(search)
if error != None:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\t%s' % error)
return False
if solution in gold_solution and (not self.exactExpansionOrder or expanded_states in gold_expanded_states):
grades.addMessage('PASS: %s' % self.path)
grades.addMessage('\tsolution:\t\t%s' % solution)
grades.addMessage('\texpanded_states:\t%s' % expanded_states)
return True
else:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\tgraph:')
for line in self.diagram.split('\n'):
grades.addMessage('\t %s' % (line,))
grades.addMessage('\tstudent solution:\t\t%s' % solution)
grades.addMessage('\tstudent expanded_states:\t%s' % expanded_states)
grades.addMessage('')
grades.addMessage('\tcorrect solution:\t\t%s' % gold_solution[0])
grades.addMessage('\tcorrect expanded_states:\t%s' % gold_expanded_states[0])
grades.addMessage('\tcorrect rev_solution:\t\t%s' % gold_solution[1])
grades.addMessage('\tcorrect rev_expanded_states:\t%s' % gold_expanded_states[1])
return False
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# open file and write comments
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
handle.write('# This solution is designed to support both right-to-left\n')
handle.write('# and left-to-right implementations.\n')
# write forward solution
solution, expanded_states, error = self.getSolInfo(search)
if error != None: raise Exception("Error in solution code: %s" % error)
handle.write('solution: "%s"\n' % ' '.join(solution))
handle.write('expanded_states: "%s"\n' % ' '.join(expanded_states))
# reverse and write backwards solution
search.REVERSE_PUSH = not search.REVERSE_PUSH
solution, expanded_states, error = self.getSolInfo(search)
if error != None: raise Exception("Error in solution code: %s" % error)
handle.write('rev_solution: "%s"\n' % ' '.join(solution))
handle.write('rev_expanded_states: "%s"\n' % ' '.join(expanded_states))
# clean up
search.REVERSE_PUSH = not search.REVERSE_PUSH
handle.close()
return True
class PacmanSearchTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(PacmanSearchTest, self).__init__(question, testDict)
self.layout_text = testDict['layout']
self.alg = testDict['algorithm']
self.layoutName = testDict['layoutName']
# TODO: sensible to have defaults like this?
self.leewayFactor = float(testDict.get('leewayFactor', '1'))
self.costFn = eval(testDict.get('costFn', 'None'))
self.searchProblemClassName = testDict.get('searchProblemClass', 'PositionSearchProblem')
self.heuristicName = testDict.get('heuristic', None)
def getSolInfo(self, search, searchAgents):
alg = getattr(search, self.alg)
lay = layout.Layout([l.strip() for
gitextract_015yh1ta/ ├── Project-1/ │ ├── VERSION │ ├── autograder.py │ ├── commands.txt │ ├── eightpuzzle.py │ ├── game.py │ ├── ghostAgents.py │ ├── grading.py │ ├── graphicsDisplay.py │ ├── graphicsUtils.py │ ├── keyboardAgents.py │ ├── layout.py │ ├── layouts/ │ │ ├── bigCorners.lay │ │ ├── bigMaze.lay │ │ ├── bigSafeSearch.lay │ │ ├── bigSearch.lay │ │ ├── boxSearch.lay │ │ ├── capsuleClassic.lay │ │ ├── contestClassic.lay │ │ ├── contoursMaze.lay │ │ ├── greedySearch.lay │ │ ├── mediumClassic.lay │ │ ├── mediumCorners.lay │ │ ├── mediumDottedMaze.lay │ │ ├── mediumMaze.lay │ │ ├── mediumSafeSearch.lay │ │ ├── mediumScaryMaze.lay │ │ ├── mediumSearch.lay │ │ ├── minimaxClassic.lay │ │ ├── oddSearch.lay │ │ ├── openClassic.lay │ │ ├── openMaze.lay │ │ ├── openSearch.lay │ │ ├── originalClassic.lay │ │ ├── smallClassic.lay │ │ ├── smallMaze.lay │ │ ├── smallSafeSearch.lay │ │ ├── smallSearch.lay │ │ ├── testClassic.lay │ │ ├── testMaze.lay │ │ ├── testSearch.lay │ │ ├── tinyCorners.lay │ │ ├── tinyMaze.lay │ │ ├── tinySafeSearch.lay │ │ ├── tinySearch.lay │ │ ├── trappedClassic.lay │ │ ├── trickyClassic.lay │ │ └── trickySearch.lay │ ├── pacman.py │ ├── pacmanAgents.py │ ├── projectParams.py │ ├── search.py │ ├── searchAgents.py │ ├── searchTestClasses.py │ ├── testClasses.py │ ├── testParser.py │ ├── test_cases/ │ │ ├── CONFIG │ │ ├── q1/ │ │ │ ├── CONFIG │ │ │ ├── graph_backtrack.solution │ │ │ ├── graph_backtrack.test │ │ │ ├── graph_bfs_vs_dfs.solution │ │ │ ├── graph_bfs_vs_dfs.test │ │ │ ├── graph_infinite.solution │ │ │ ├── graph_infinite.test │ │ │ ├── graph_manypaths.solution │ │ │ ├── graph_manypaths.test │ │ │ ├── pacman_1.solution │ │ │ └── pacman_1.test │ │ ├── q2/ │ │ │ ├── CONFIG │ │ │ ├── graph_backtrack.solution │ │ │ ├── graph_backtrack.test │ │ │ ├── graph_bfs_vs_dfs.solution │ │ │ ├── graph_bfs_vs_dfs.test │ │ │ ├── graph_infinite.solution │ │ │ ├── graph_infinite.test │ │ │ ├── graph_manypaths.solution │ │ │ ├── graph_manypaths.test │ │ │ ├── pacman_1.solution │ │ │ └── pacman_1.test │ │ ├── q3/ │ │ │ ├── CONFIG │ │ │ ├── graph_backtrack.solution │ │ │ ├── graph_backtrack.test │ │ │ ├── graph_bfs_vs_dfs.solution │ │ │ ├── graph_bfs_vs_dfs.test │ │ │ ├── graph_infinite.solution │ │ │ ├── graph_infinite.test │ │ │ ├── graph_manypaths.solution │ │ │ ├── graph_manypaths.test │ │ │ ├── ucs_0_graph.solution │ │ │ ├── ucs_0_graph.test │ │ │ ├── ucs_1_problemC.solution │ │ │ ├── ucs_1_problemC.test │ │ │ ├── ucs_2_problemE.solution │ │ │ ├── ucs_2_problemE.test │ │ │ ├── ucs_3_problemW.solution │ │ │ ├── ucs_3_problemW.test │ │ │ ├── ucs_4_testSearch.solution │ │ │ ├── ucs_4_testSearch.test │ │ │ ├── ucs_5_goalAtDequeue.solution │ │ │ └── ucs_5_goalAtDequeue.test │ │ ├── q4/ │ │ │ ├── CONFIG │ │ │ ├── astar_0.solution │ │ │ ├── astar_0.test │ │ │ ├── astar_1_graph_heuristic.solution │ │ │ ├── astar_1_graph_heuristic.test │ │ │ ├── astar_2_manhattan.solution │ │ │ ├── astar_2_manhattan.test │ │ │ ├── astar_3_goalAtDequeue.solution │ │ │ ├── astar_3_goalAtDequeue.test │ │ │ ├── graph_backtrack.solution │ │ │ ├── graph_backtrack.test │ │ │ ├── graph_manypaths.solution │ │ │ └── graph_manypaths.test │ │ ├── q5/ │ │ │ ├── CONFIG │ │ │ ├── corner_tiny_corner.solution │ │ │ └── corner_tiny_corner.test │ │ ├── q6/ │ │ │ ├── CONFIG │ │ │ ├── corner_sanity_1.solution │ │ │ ├── corner_sanity_1.test │ │ │ ├── corner_sanity_2.solution │ │ │ ├── corner_sanity_2.test │ │ │ ├── corner_sanity_3.solution │ │ │ ├── corner_sanity_3.test │ │ │ ├── medium_corners.solution │ │ │ └── medium_corners.test │ │ ├── q7/ │ │ │ ├── CONFIG │ │ │ ├── food_heuristic_1.solution │ │ │ ├── food_heuristic_1.test │ │ │ ├── food_heuristic_10.solution │ │ │ ├── food_heuristic_10.test │ │ │ ├── food_heuristic_11.solution │ │ │ ├── food_heuristic_11.test │ │ │ ├── food_heuristic_12.solution │ │ │ ├── food_heuristic_12.test │ │ │ ├── food_heuristic_13.solution │ │ │ ├── food_heuristic_13.test │ │ │ ├── food_heuristic_14.solution │ │ │ ├── food_heuristic_14.test │ │ │ ├── food_heuristic_15.solution │ │ │ ├── food_heuristic_15.test │ │ │ ├── food_heuristic_16.solution │ │ │ ├── food_heuristic_16.test │ │ │ ├── food_heuristic_17.solution │ │ │ ├── food_heuristic_17.test │ │ │ ├── food_heuristic_2.solution │ │ │ ├── food_heuristic_2.test │ │ │ ├── food_heuristic_3.solution │ │ │ ├── food_heuristic_3.test │ │ │ ├── food_heuristic_4.solution │ │ │ ├── food_heuristic_4.test │ │ │ ├── food_heuristic_5.solution │ │ │ ├── food_heuristic_5.test │ │ │ ├── food_heuristic_6.solution │ │ │ ├── food_heuristic_6.test │ │ │ ├── food_heuristic_7.solution │ │ │ ├── food_heuristic_7.test │ │ │ ├── food_heuristic_8.solution │ │ │ ├── food_heuristic_8.test │ │ │ ├── food_heuristic_9.solution │ │ │ ├── food_heuristic_9.test │ │ │ ├── food_heuristic_grade_tricky.solution │ │ │ └── food_heuristic_grade_tricky.test │ │ └── q8/ │ │ ├── CONFIG │ │ ├── closest_dot_1.solution │ │ ├── closest_dot_1.test │ │ ├── closest_dot_10.solution │ │ ├── closest_dot_10.test │ │ ├── closest_dot_11.solution │ │ ├── closest_dot_11.test │ │ ├── closest_dot_12.solution │ │ ├── closest_dot_12.test │ │ ├── closest_dot_13.solution │ │ ├── closest_dot_13.test │ │ ├── closest_dot_2.solution │ │ ├── closest_dot_2.test │ │ ├── closest_dot_3.solution │ │ ├── closest_dot_3.test │ │ ├── closest_dot_4.solution │ │ ├── closest_dot_4.test │ │ ├── closest_dot_5.solution │ │ ├── closest_dot_5.test │ │ ├── closest_dot_6.solution │ │ ├── closest_dot_6.test │ │ ├── closest_dot_7.solution │ │ ├── closest_dot_7.test │ │ ├── closest_dot_8.solution │ │ ├── closest_dot_8.test │ │ ├── closest_dot_9.solution │ │ └── closest_dot_9.test │ ├── textDisplay.py │ └── util.py ├── Project-2/ │ ├── VERSION │ ├── autograder.py │ ├── game.py │ ├── ghostAgents.py │ ├── grading.py │ ├── graphicsDisplay.py │ ├── graphicsUtils.py │ ├── keyboardAgents.py │ ├── layout.py │ ├── layouts/ │ │ ├── capsuleClassic.lay │ │ ├── contestClassic.lay │ │ ├── mediumClassic.lay │ │ ├── minimaxClassic.lay │ │ ├── openClassic.lay │ │ ├── originalClassic.lay │ │ ├── smallClassic.lay │ │ ├── testClassic.lay │ │ ├── trappedClassic.lay │ │ └── trickyClassic.lay │ ├── multiAgents.py │ ├── multiagentTestClasses.py │ ├── pacman.py │ ├── pacmanAgents.py │ ├── projectParams.py │ ├── testClasses.py │ ├── testParser.py │ ├── test_cases/ │ │ ├── CONFIG │ │ ├── extra/ │ │ │ ├── CONFIG │ │ │ └── grade-agent.test │ │ ├── q1/ │ │ │ ├── CONFIG │ │ │ ├── grade-agent.solution │ │ │ └── grade-agent.test │ │ ├── q2/ │ │ │ ├── 0-lecture-6-tree.solution │ │ │ ├── 0-lecture-6-tree.test │ │ │ ├── 0-small-tree.solution │ │ │ ├── 0-small-tree.test │ │ │ ├── 1-1-minmax.solution │ │ │ ├── 1-1-minmax.test │ │ │ ├── 1-2-minmax.solution │ │ │ ├── 1-2-minmax.test │ │ │ ├── 1-3-minmax.solution │ │ │ ├── 1-3-minmax.test │ │ │ ├── 1-4-minmax.solution │ │ │ ├── 1-4-minmax.test │ │ │ ├── 1-5-minmax.solution │ │ │ ├── 1-5-minmax.test │ │ │ ├── 1-6-minmax.solution │ │ │ ├── 1-6-minmax.test │ │ │ ├── 1-7-minmax.solution │ │ │ ├── 1-7-minmax.test │ │ │ ├── 1-8-minmax.solution │ │ │ ├── 1-8-minmax.test │ │ │ ├── 2-1a-vary-depth.solution │ │ │ ├── 2-1a-vary-depth.test │ │ │ ├── 2-1b-vary-depth.solution │ │ │ ├── 2-1b-vary-depth.test │ │ │ ├── 2-2a-vary-depth.solution │ │ │ ├── 2-2a-vary-depth.test │ │ │ ├── 2-2b-vary-depth.solution │ │ │ ├── 2-2b-vary-depth.test │ │ │ ├── 2-3a-vary-depth.solution │ │ │ ├── 2-3a-vary-depth.test │ │ │ ├── 2-3b-vary-depth.solution │ │ │ ├── 2-3b-vary-depth.test │ │ │ ├── 2-4a-vary-depth.solution │ │ │ ├── 2-4a-vary-depth.test │ │ │ ├── 2-4b-vary-depth.solution │ │ │ ├── 2-4b-vary-depth.test │ │ │ ├── 2-one-ghost-3level.solution │ │ │ ├── 2-one-ghost-3level.test │ │ │ ├── 3-one-ghost-4level.solution │ │ │ ├── 3-one-ghost-4level.test │ │ │ ├── 4-two-ghosts-3level.solution │ │ │ ├── 4-two-ghosts-3level.test │ │ │ ├── 5-two-ghosts-4level.solution │ │ │ ├── 5-two-ghosts-4level.test │ │ │ ├── 6-tied-root.solution │ │ │ ├── 6-tied-root.test │ │ │ ├── 7-1a-check-depth-one-ghost.solution │ │ │ ├── 7-1a-check-depth-one-ghost.test │ │ │ ├── 7-1b-check-depth-one-ghost.solution │ │ │ ├── 7-1b-check-depth-one-ghost.test │ │ │ ├── 7-1c-check-depth-one-ghost.solution │ │ │ ├── 7-1c-check-depth-one-ghost.test │ │ │ ├── 7-2a-check-depth-two-ghosts.solution │ │ │ ├── 7-2a-check-depth-two-ghosts.test │ │ │ ├── 7-2b-check-depth-two-ghosts.solution │ │ │ ├── 7-2b-check-depth-two-ghosts.test │ │ │ ├── 7-2c-check-depth-two-ghosts.solution │ │ │ ├── 7-2c-check-depth-two-ghosts.test │ │ │ ├── 8-pacman-game.solution │ │ │ ├── 8-pacman-game.test │ │ │ └── CONFIG │ │ ├── q3/ │ │ │ ├── 0-lecture-6-tree.solution │ │ │ ├── 0-lecture-6-tree.test │ │ │ ├── 0-small-tree.solution │ │ │ ├── 0-small-tree.test │ │ │ ├── 1-1-minmax.solution │ │ │ ├── 1-1-minmax.test │ │ │ ├── 1-2-minmax.solution │ │ │ ├── 1-2-minmax.test │ │ │ ├── 1-3-minmax.solution │ │ │ ├── 1-3-minmax.test │ │ │ ├── 1-4-minmax.solution │ │ │ ├── 1-4-minmax.test │ │ │ ├── 1-5-minmax.solution │ │ │ ├── 1-5-minmax.test │ │ │ ├── 1-6-minmax.solution │ │ │ ├── 1-6-minmax.test │ │ │ ├── 1-7-minmax.solution │ │ │ ├── 1-7-minmax.test │ │ │ ├── 1-8-minmax.solution │ │ │ ├── 1-8-minmax.test │ │ │ ├── 2-1a-vary-depth.solution │ │ │ ├── 2-1a-vary-depth.test │ │ │ ├── 2-1b-vary-depth.solution │ │ │ ├── 2-1b-vary-depth.test │ │ │ ├── 2-2a-vary-depth.solution │ │ │ ├── 2-2a-vary-depth.test │ │ │ ├── 2-2b-vary-depth.solution │ │ │ ├── 2-2b-vary-depth.test │ │ │ ├── 2-3a-vary-depth.solution │ │ │ ├── 2-3a-vary-depth.test │ │ │ ├── 2-3b-vary-depth.solution │ │ │ ├── 2-3b-vary-depth.test │ │ │ ├── 2-4a-vary-depth.solution │ │ │ ├── 2-4a-vary-depth.test │ │ │ ├── 2-4b-vary-depth.solution │ │ │ ├── 2-4b-vary-depth.test │ │ │ ├── 2-one-ghost-3level.solution │ │ │ ├── 2-one-ghost-3level.test │ │ │ ├── 3-one-ghost-4level.solution │ │ │ ├── 3-one-ghost-4level.test │ │ │ ├── 4-two-ghosts-3level.solution │ │ │ ├── 4-two-ghosts-3level.test │ │ │ ├── 5-two-ghosts-4level.solution │ │ │ ├── 5-two-ghosts-4level.test │ │ │ ├── 6-tied-root.solution │ │ │ ├── 6-tied-root.test │ │ │ ├── 7-1a-check-depth-one-ghost.solution │ │ │ ├── 7-1a-check-depth-one-ghost.test │ │ │ ├── 7-1b-check-depth-one-ghost.solution │ │ │ ├── 7-1b-check-depth-one-ghost.test │ │ │ ├── 7-1c-check-depth-one-ghost.solution │ │ │ ├── 7-1c-check-depth-one-ghost.test │ │ │ ├── 7-2a-check-depth-two-ghosts.solution │ │ │ ├── 7-2a-check-depth-two-ghosts.test │ │ │ ├── 7-2b-check-depth-two-ghosts.solution │ │ │ ├── 7-2b-check-depth-two-ghosts.test │ │ │ ├── 7-2c-check-depth-two-ghosts.solution │ │ │ ├── 7-2c-check-depth-two-ghosts.test │ │ │ ├── 8-pacman-game.solution │ │ │ ├── 8-pacman-game.test │ │ │ └── CONFIG │ │ ├── q4/ │ │ │ ├── 0-expectimax1.solution │ │ │ ├── 0-expectimax1.test │ │ │ ├── 1-expectimax2.solution │ │ │ ├── 1-expectimax2.test │ │ │ ├── 2-one-ghost-3level.solution │ │ │ ├── 2-one-ghost-3level.test │ │ │ ├── 3-one-ghost-4level.solution │ │ │ ├── 3-one-ghost-4level.test │ │ │ ├── 4-two-ghosts-3level.solution │ │ │ ├── 4-two-ghosts-3level.test │ │ │ ├── 5-two-ghosts-4level.solution │ │ │ ├── 5-two-ghosts-4level.test │ │ │ ├── 6-1a-check-depth-one-ghost.solution │ │ │ ├── 6-1a-check-depth-one-ghost.test │ │ │ ├── 6-1b-check-depth-one-ghost.solution │ │ │ ├── 6-1b-check-depth-one-ghost.test │ │ │ ├── 6-1c-check-depth-one-ghost.solution │ │ │ ├── 6-1c-check-depth-one-ghost.test │ │ │ ├── 6-2a-check-depth-two-ghosts.solution │ │ │ ├── 6-2a-check-depth-two-ghosts.test │ │ │ ├── 6-2b-check-depth-two-ghosts.solution │ │ │ ├── 6-2b-check-depth-two-ghosts.test │ │ │ ├── 6-2c-check-depth-two-ghosts.solution │ │ │ ├── 6-2c-check-depth-two-ghosts.test │ │ │ ├── 7-pacman-game.solution │ │ │ ├── 7-pacman-game.test │ │ │ └── CONFIG │ │ └── q5/ │ │ ├── CONFIG │ │ ├── grade-agent.solution │ │ └── grade-agent.test │ ├── textDisplay.py │ └── util.py ├── Project-3/ │ ├── VERSION │ ├── analysis.py │ ├── autograder.py │ ├── crawler.py │ ├── environment.py │ ├── featureExtractors.py │ ├── game.py │ ├── ghostAgents.py │ ├── grading.py │ ├── graphicsCrawlerDisplay.py │ ├── graphicsDisplay.py │ ├── graphicsGridworldDisplay.py │ ├── graphicsUtils.py │ ├── gridworld.py │ ├── keyboardAgents.py │ ├── layout.py │ ├── layouts/ │ │ ├── capsuleClassic.lay │ │ ├── contestClassic.lay │ │ ├── mediumClassic.lay │ │ ├── mediumGrid.lay │ │ ├── minimaxClassic.lay │ │ ├── openClassic.lay │ │ ├── originalClassic.lay │ │ ├── smallClassic.lay │ │ ├── smallGrid.lay │ │ ├── testClassic.lay │ │ ├── trappedClassic.lay │ │ └── trickyClassic.lay │ ├── learningAgents.py │ ├── mdp.py │ ├── pacman.py │ ├── pacmanAgents.py │ ├── projectParams.py │ ├── qlearningAgents.py │ ├── reinforcementTestClasses.py │ ├── testClasses.py │ ├── testParser.py │ ├── test_cases/ │ │ ├── CONFIG │ │ ├── q1/ │ │ │ ├── 1-tinygrid.solution │ │ │ ├── 1-tinygrid.test │ │ │ ├── 2-tinygrid-noisy.solution │ │ │ ├── 2-tinygrid-noisy.test │ │ │ ├── 3-bridge.solution │ │ │ ├── 3-bridge.test │ │ │ ├── 4-discountgrid.solution │ │ │ ├── 4-discountgrid.test │ │ │ └── CONFIG │ │ ├── q2/ │ │ │ ├── 1-bridge-grid.solution │ │ │ ├── 1-bridge-grid.test │ │ │ └── CONFIG │ │ ├── q3/ │ │ │ ├── 1-question-3.1.solution │ │ │ ├── 1-question-3.1.test │ │ │ ├── 2-question-3.2.solution │ │ │ ├── 2-question-3.2.test │ │ │ ├── 3-question-3.3.solution │ │ │ ├── 3-question-3.3.test │ │ │ ├── 4-question-3.4.solution │ │ │ ├── 4-question-3.4.test │ │ │ ├── 5-question-3.5.solution │ │ │ ├── 5-question-3.5.test │ │ │ └── CONFIG │ │ ├── q4/ │ │ │ ├── 1-tinygrid.solution │ │ │ ├── 1-tinygrid.test │ │ │ ├── 2-tinygrid-noisy.solution │ │ │ ├── 2-tinygrid-noisy.test │ │ │ ├── 3-bridge.solution │ │ │ ├── 3-bridge.test │ │ │ ├── 4-discountgrid.solution │ │ │ ├── 4-discountgrid.test │ │ │ └── CONFIG │ │ ├── q5/ │ │ │ ├── 1-tinygrid.solution │ │ │ ├── 1-tinygrid.test │ │ │ ├── 2-tinygrid-noisy.solution │ │ │ ├── 2-tinygrid-noisy.test │ │ │ ├── 3-bridge.solution │ │ │ ├── 3-bridge.test │ │ │ ├── 4-discountgrid.solution │ │ │ ├── 4-discountgrid.test │ │ │ └── CONFIG │ │ ├── q6/ │ │ │ ├── CONFIG │ │ │ ├── grade-agent.solution │ │ │ └── grade-agent.test │ │ ├── q7/ │ │ │ ├── CONFIG │ │ │ ├── grade-agent.solution │ │ │ └── grade-agent.test │ │ └── q8/ │ │ ├── 1-tinygrid.solution │ │ ├── 1-tinygrid.test │ │ ├── 2-tinygrid-noisy.solution │ │ ├── 2-tinygrid-noisy.test │ │ ├── 3-bridge.solution │ │ ├── 3-bridge.test │ │ ├── 4-discountgrid.solution │ │ ├── 4-discountgrid.test │ │ ├── 5-coord-extractor.solution │ │ ├── 5-coord-extractor.test │ │ └── CONFIG │ ├── textDisplay.py │ ├── textGridworldDisplay.py │ ├── util.py │ └── valueIterationAgents.py ├── Project-4/ │ ├── VERSION │ ├── autograder.py │ ├── busters.py │ ├── bustersAgents.py │ ├── bustersGhostAgents.py │ ├── distanceCalculator.py │ ├── game.py │ ├── ghostAgents.py │ ├── grading.py │ ├── graphicsDisplay.py │ ├── graphicsUtils.py │ ├── inference.py │ ├── keyboardAgents.py │ ├── layout.py │ ├── layouts/ │ │ ├── bigHunt.lay │ │ ├── oneHunt.lay │ │ ├── openHunt.lay │ │ └── smallHunt.lay │ ├── pacman.py │ ├── projectParams.py │ ├── testClasses.py │ ├── testParser.py │ ├── test_cases/ │ │ ├── CONFIG │ │ ├── q1/ │ │ │ ├── 1-ExactObserve.solution │ │ │ ├── 1-ExactObserve.test │ │ │ ├── 2-ExactObserve.solution │ │ │ ├── 2-ExactObserve.test │ │ │ ├── 3-ExactObserve.solution │ │ │ ├── 3-ExactObserve.test │ │ │ ├── 4-ExactObserve.solution │ │ │ ├── 4-ExactObserve.test │ │ │ └── CONFIG │ │ ├── q2/ │ │ │ ├── 1-ExactElapse.solution │ │ │ ├── 1-ExactElapse.test │ │ │ ├── 2-ExactElapse.solution │ │ │ ├── 2-ExactElapse.test │ │ │ ├── 3-ExactElapse.solution │ │ │ ├── 3-ExactElapse.test │ │ │ ├── 4-ExactElapse.solution │ │ │ ├── 4-ExactElapse.test │ │ │ └── CONFIG │ │ ├── q3/ │ │ │ ├── 1-ExactObserveElapse.solution │ │ │ ├── 1-ExactObserveElapse.test │ │ │ ├── 2-ExactObserveElapse.solution │ │ │ ├── 2-ExactObserveElapse.test │ │ │ ├── 3-gameScoreTest.solution │ │ │ ├── 3-gameScoreTest.test │ │ │ └── CONFIG │ │ ├── q4/ │ │ │ ├── 1-ParticleObserve.solution │ │ │ ├── 1-ParticleObserve.test │ │ │ ├── 2-ParticleObserve.solution │ │ │ ├── 2-ParticleObserve.test │ │ │ ├── 3-ParticleObserve.solution │ │ │ ├── 3-ParticleObserve.test │ │ │ ├── 4-ParticleObserve.solution │ │ │ ├── 4-ParticleObserve.test │ │ │ ├── 5-ParticleObserve.solution │ │ │ ├── 5-ParticleObserve.test │ │ │ ├── 6-ParticleObserve.solution │ │ │ ├── 6-ParticleObserve.test │ │ │ ├── 7-ParticleObserve.solution │ │ │ ├── 7-ParticleObserve.test │ │ │ └── CONFIG │ │ ├── q5/ │ │ │ ├── 1-ParticleElapse.solution │ │ │ ├── 1-ParticleElapse.test │ │ │ ├── 2-ParticleElapse.solution │ │ │ ├── 2-ParticleElapse.test │ │ │ ├── 3-ParticleElapse.solution │ │ │ ├── 3-ParticleElapse.test │ │ │ ├── 4-ParticleElapse.solution │ │ │ ├── 4-ParticleElapse.test │ │ │ ├── 5-ParticleElapse.solution │ │ │ ├── 5-ParticleElapse.test │ │ │ ├── 6-ParticleElapse.solution │ │ │ ├── 6-ParticleElapse.test │ │ │ └── CONFIG │ │ ├── q6/ │ │ │ ├── 1-JointParticleObserve.solution │ │ │ ├── 1-JointParticleObserve.test │ │ │ ├── 2-JointParticleObserve.solution │ │ │ ├── 2-JointParticleObserve.test │ │ │ ├── 3-JointParticleObserve.solution │ │ │ ├── 3-JointParticleObserve.test │ │ │ ├── 4-JointParticleObserve.solution │ │ │ ├── 4-JointParticleObserve.test │ │ │ ├── 5-JointParticleObserve.solution │ │ │ ├── 5-JointParticleObserve.test │ │ │ └── CONFIG │ │ └── q7/ │ │ ├── 1-JointParticleElapse.solution │ │ ├── 1-JointParticleElapse.test │ │ ├── 2-JointParticleElapse.solution │ │ ├── 2-JointParticleElapse.test │ │ ├── 3-JointParticleObserveElapse.solution │ │ ├── 3-JointParticleObserveElapse.test │ │ └── CONFIG │ ├── textDisplay.py │ ├── trackingTestClasses.py │ └── util.py ├── Project-5/ │ ├── VERSION │ ├── answers.py │ ├── autograder.py │ ├── classificationAgents.py │ ├── classificationMethod.py │ ├── classificationTestClasses.py │ ├── data/ │ │ ├── digitdata/ │ │ │ ├── testimages │ │ │ ├── testlabels │ │ │ ├── trainingimages │ │ │ ├── traininglabels │ │ │ ├── validationimages │ │ │ └── validationlabels │ │ ├── facedata/ │ │ │ ├── facedatatest │ │ │ ├── facedatatestlabels │ │ │ ├── facedatatrain │ │ │ ├── facedatatrainlabels │ │ │ ├── facedatavalidation │ │ │ └── facedatavalidationlabels │ │ └── pacmandata/ │ │ ├── contest_test.pkl │ │ ├── contest_training.pkl │ │ ├── contest_validation.pkl │ │ ├── food_test.pkl │ │ ├── food_training.pkl │ │ ├── food_validation.pkl │ │ ├── stop_test.pkl │ │ ├── stop_training.pkl │ │ ├── stop_validation.pkl │ │ ├── suicide_test.pkl │ │ ├── suicide_training.pkl │ │ └── suicide_validation.pkl │ ├── dataClassifier.py │ ├── game.py │ ├── ghostAgents.py │ ├── grading.py │ ├── graphicsDisplay.py │ ├── graphicsUtils.py │ ├── images/ │ │ └── img2 │ ├── keyboardAgents.py │ ├── layout.py │ ├── layouts/ │ │ ├── capsuleClassic.lay │ │ ├── contestClassic.lay │ │ ├── mediumClassic.lay │ │ ├── minimaxClassic.lay │ │ ├── openClassic.lay │ │ ├── originalClassic.lay │ │ ├── smallClassic.lay │ │ ├── testClassic.lay │ │ ├── trappedClassic.lay │ │ └── trickyClassic.lay │ ├── mira.py │ ├── mostFrequent.py │ ├── naiveBayes.py │ ├── pacman.py │ ├── pacmanAgents.py │ ├── pacmandata/ │ │ ├── contest_test.pkl │ │ ├── contest_training.pkl │ │ ├── contest_validation.pkl │ │ ├── food_test.pkl │ │ ├── food_training.pkl │ │ ├── food_validation.pkl │ │ ├── stop_test.pkl │ │ ├── stop_training.pkl │ │ ├── stop_validation.pkl │ │ ├── suicide_test.pkl │ │ ├── suicide_training.pkl │ │ └── suicide_validation.pkl │ ├── perceptron.py │ ├── perceptron_pacman.py │ ├── projectParams.py │ ├── samples.py │ ├── testClasses.py │ ├── testParser.py │ ├── test_cases/ │ │ ├── CONFIG │ │ ├── q1/ │ │ │ ├── CONFIG │ │ │ ├── grade.solution │ │ │ └── grade.test │ │ ├── q2/ │ │ │ ├── CONFIG │ │ │ ├── grade.solution │ │ │ └── grade.test │ │ ├── q3/ │ │ │ ├── CONFIG │ │ │ ├── grade.solution │ │ │ └── grade.test │ │ ├── q4/ │ │ │ ├── CONFIG │ │ │ ├── grade.solution │ │ │ └── grade.test │ │ ├── q5/ │ │ │ ├── CONFIG │ │ │ ├── contest.solution │ │ │ ├── contest.test │ │ │ ├── suicide.solution │ │ │ └── suicide.test │ │ └── q6/ │ │ ├── CONFIG │ │ ├── contest.solution │ │ ├── contest.test │ │ ├── suicide.solution │ │ └── suicide.test │ ├── textDisplay.py │ └── util.py └── README.md
SYMBOL INDEX (2632 symbols across 105 files)
FILE: Project-1/autograder.py
function readCommand (line 31) | def readCommand(argv):
function confirmGenerate (line 83) | def confirmGenerate():
function setModuleName (line 100) | def setModuleName(module, filename):
function loadModuleString (line 118) | def loadModuleString(moduleSource):
function loadModuleFile (line 131) | def loadModuleFile(moduleName, filePath):
function readFile (line 136) | def readFile(path, root=""):
function splitStrings (line 173) | def splitStrings(d):
function printTest (line 184) | def printTest(testDict, solutionDict):
function runTest (line 194) | def runTest(testName, moduleDict, printTestCase=False, display=None):
function getDepends (line 219) | def getDepends(testParser, testRoot, question):
function getTestSubdirs (line 230) | def getTestSubdirs(testParser, testRoot, questionToGrade):
function evaluate (line 243) | def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR...
function getDisplay (line 310) | def getDisplay(graphicsByDefault, options=None):
FILE: Project-1/eightpuzzle.py
class EightPuzzleState (line 20) | class EightPuzzleState:
method __init__ (line 30) | def __init__( self, numbers ):
method isGoal (line 62) | def isGoal( self ):
method legalMoves (line 88) | def legalMoves( self ):
method result (line 110) | def result(self, move):
method __eq__ (line 149) | def __eq__(self, other):
method __hash__ (line 163) | def __hash__(self):
method __getAsciiString (line 166) | def __getAsciiString(self):
method __str__ (line 183) | def __str__(self):
class EightPuzzleSearchProblem (line 188) | class EightPuzzleSearchProblem(search.SearchProblem):
method __init__ (line 194) | def __init__(self,puzzle):
method getStartState (line 198) | def getStartState(self):
method isGoalState (line 201) | def isGoalState(self,state):
method getSuccessors (line 204) | def getSuccessors(self,state):
method getCostOfActions (line 215) | def getCostOfActions(self, actions):
function loadEightPuzzle (line 231) | def loadEightPuzzle(puzzleNumber):
function createRandomEightPuzzle (line 251) | def createRandomEightPuzzle(moves=100):
FILE: Project-1/game.py
class Agent (line 32) | class Agent:
method __init__ (line 39) | def __init__(self, index=0):
method getAction (line 42) | def getAction(self, state):
class Directions (line 49) | class Directions:
class Configuration (line 70) | class Configuration:
method __init__ (line 79) | def __init__(self, pos, direction):
method getPosition (line 83) | def getPosition(self):
method getDirection (line 86) | def getDirection(self):
method isInteger (line 89) | def isInteger(self):
method __eq__ (line 93) | def __eq__(self, other):
method __hash__ (line 97) | def __hash__(self):
method __str__ (line 102) | def __str__(self):
method generateSuccessor (line 105) | def generateSuccessor(self, vector):
class AgentState (line 120) | class AgentState:
method __init__ (line 125) | def __init__( self, startConfiguration, isPacman ):
method __str__ (line 133) | def __str__( self ):
method __eq__ (line 139) | def __eq__( self, other ):
method __hash__ (line 144) | def __hash__(self):
method copy (line 147) | def copy( self ):
method getPosition (line 155) | def getPosition(self):
method getDirection (line 159) | def getDirection(self):
class Grid (line 162) | class Grid:
method __init__ (line 170) | def __init__(self, width, height, initialValue=False, bitRepresentatio...
method __getitem__ (line 180) | def __getitem__(self, i):
method __setitem__ (line 183) | def __setitem__(self, key, item):
method __str__ (line 186) | def __str__(self):
method __eq__ (line 191) | def __eq__(self, other):
method __hash__ (line 195) | def __hash__(self):
method copy (line 206) | def copy(self):
method deepCopy (line 211) | def deepCopy(self):
method shallowCopy (line 214) | def shallowCopy(self):
method count (line 219) | def count(self, item =True ):
method asList (line 222) | def asList(self, key = True):
method packBits (line 229) | def packBits(self):
method _cellIndexToPosition (line 248) | def _cellIndexToPosition(self, index):
method _unpackBits (line 253) | def _unpackBits(self, bits):
method _unpackInt (line 265) | def _unpackInt(self, packed, size):
function reconstituteGrid (line 277) | def reconstituteGrid(bitRep):
class Actions (line 287) | class Actions:
method reverseDirection (line 302) | def reverseDirection(action):
method vectorToDirection (line 314) | def vectorToDirection(vector):
method directionToVector (line 327) | def directionToVector(direction, speed = 1.0):
method getPossibleActions (line 332) | def getPossibleActions(config, walls):
method getLegalNeighbors (line 351) | def getLegalNeighbors(position, walls):
method getSuccessor (line 365) | def getSuccessor(position, action):
class GameStateData (line 371) | class GameStateData:
method __init__ (line 375) | def __init__( self, prevState = None ):
method deepCopy (line 395) | def deepCopy( self ):
method copyAgentStates (line 405) | def copyAgentStates( self, agentStates ):
method __eq__ (line 411) | def __eq__( self, other ):
method __hash__ (line 423) | def __hash__( self ):
method __str__ (line 435) | def __str__( self ):
method _foodWallStr (line 460) | def _foodWallStr( self, hasFood, hasWall ):
method _pacStr (line 468) | def _pacStr( self, dir ):
method _ghostStr (line 477) | def _ghostStr( self, dir ):
method initialize (line 487) | def initialize( self, layout, numGhostAgents ):
class Game (line 513) | class Game:
method __init__ (line 518) | def __init__( self, agents, display, rules, startingIndex=0, muteAgent...
method getProgress (line 534) | def getProgress(self):
method _agentCrash (line 540) | def _agentCrash( self, agentIndex, quiet=False):
method mute (line 550) | def mute(self, agentIndex):
method unmute (line 559) | def unmute(self):
method run (line 567) | def run( self ):
FILE: Project-1/ghostAgents.py
class GhostAgent (line 22) | class GhostAgent( Agent ):
method __init__ (line 23) | def __init__( self, index ):
method getAction (line 26) | def getAction( self, state ):
method getDistribution (line 33) | def getDistribution(self, state):
class RandomGhost (line 37) | class RandomGhost( GhostAgent ):
method getDistribution (line 39) | def getDistribution( self, state ):
class DirectionalGhost (line 45) | class DirectionalGhost( GhostAgent ):
method __init__ (line 47) | def __init__( self, index, prob_attack=0.8, prob_scaredFlee=0.8 ):
method getDistribution (line 52) | def getDistribution( self, state ):
FILE: Project-1/grading.py
class Grades (line 25) | class Grades:
method __init__ (line 27) | def __init__(self, projectName, questionsAndMaxesList, edxOutput=False...
method addPrereq (line 48) | def addPrereq(self, question, prereq):
method grade (line 51) | def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
method addExceptionMessage (line 139) | def addExceptionMessage(self, q, inst, traceback):
method addErrorHints (line 149) | def addErrorHints(self, exceptionMap, errorInstance, questionNum):
method produceOutput (line 171) | def produceOutput(self):
method fail (line 227) | def fail(self, message, raw=False):
method assignZeroCredit (line 233) | def assignZeroCredit(self):
method addPoints (line 236) | def addPoints(self, amt):
method deductPoints (line 239) | def deductPoints(self, amt):
method assignFullCredit (line 242) | def assignFullCredit(self, message="", raw=False):
method addMessage (line 247) | def addMessage(self, message, raw=False):
method addMessageToEmail (line 256) | def addMessageToEmail(self, message):
class Counter (line 267) | class Counter(dict):
method __getitem__ (line 271) | def __getitem__(self, idx):
method totalCount (line 277) | def totalCount(self):
FILE: Project-1/graphicsDisplay.py
class InfoPane (line 82) | class InfoPane:
method __init__ (line 83) | def __init__(self, layout, gridSize):
method toScreen (line 92) | def toScreen(self, pos, y = None):
method drawPane (line 105) | def drawPane(self):
method initializeGhostDistances (line 108) | def initializeGhostDistances(self, distances):
method updateScore (line 121) | def updateScore(self, score):
method setTeam (line 124) | def setTeam(self, isBlue):
method updateGhostDistances (line 129) | def updateGhostDistances(self, distances):
method drawGhost (line 136) | def drawGhost(self):
method drawPacman (line 139) | def drawPacman(self):
method drawWarning (line 142) | def drawWarning(self):
method clearIcon (line 145) | def clearIcon(self):
method updateMessage (line 148) | def updateMessage(self, message):
method clearMessage (line 151) | def clearMessage(self):
class PacmanGraphics (line 155) | class PacmanGraphics:
method __init__ (line 156) | def __init__(self, zoom=1.0, frameTime=0.0, capture=False):
method checkNullDisplay (line 165) | def checkNullDisplay(self):
method initialize (line 168) | def initialize(self, state, isBlue = False):
method startGraphics (line 180) | def startGraphics(self, state):
method drawDistributions (line 189) | def drawDistributions(self, state):
method drawStaticObjects (line 204) | def drawStaticObjects(self, state):
method drawAgentObjects (line 211) | def drawAgentObjects(self, state):
method swapImages (line 222) | def swapImages(self, agentIndex, newState):
method update (line 236) | def update(self, newState):
method make_window (line 256) | def make_window(self, width, height):
method drawPacman (line 267) | def drawPacman(self, pacman, index):
method getEndpoints (line 286) | def getEndpoints(self, direction, position=(0,0)):
method movePacman (line 302) | def movePacman(self, position, direction, image):
method animatePacman (line 309) | def animatePacman(self, pacman, prevPacman, image):
method getGhostColor (line 329) | def getGhostColor(self, ghost, ghostIndex):
method drawGhost (line 335) | def drawGhost(self, ghost, agentIndex):
method moveEyes (line 371) | def moveEyes(self, pos, dir, eyes):
method moveGhost (line 388) | def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
method getPosition (line 405) | def getPosition(self, agentState):
method getDirection (line 409) | def getDirection(self, agentState):
method finish (line 413) | def finish(self):
method to_screen (line 416) | def to_screen(self, point):
method to_screen2 (line 424) | def to_screen2(self, point):
method drawWalls (line 431) | def drawWalls(self, wallMatrix):
method isWall (line 517) | def isWall(self, x, y, walls):
method drawFood (line 524) | def drawFood(self, foodMatrix ):
method drawCapsules (line 544) | def drawCapsules(self, capsules ):
method removeFood (line 556) | def removeFood(self, cell, foodImages ):
method removeCapsule (line 560) | def removeCapsule(self, cell, capsuleImages ):
method drawExpandedCells (line 564) | def drawExpandedCells(self, cells):
method clearExpandedCells (line 583) | def clearExpandedCells(self):
method updateDistributions (line 589) | def updateDistributions(self, distributions):
class FirstPersonPacmanGraphics (line 611) | class FirstPersonPacmanGraphics(PacmanGraphics):
method __init__ (line 612) | def __init__(self, zoom = 1.0, showGhosts = True, capture = False, fra...
method initialize (line 617) | def initialize(self, state, isBlue = False):
method lookAhead (line 634) | def lookAhead(self, config, state):
method getGhostColor (line 648) | def getGhostColor(self, ghost, ghostIndex):
method getPosition (line 651) | def getPosition(self, ghostState):
function add (line 657) | def add(x, y):
function saveFrame (line 672) | def saveFrame():
FILE: Project-1/graphicsUtils.py
function formatColor (line 35) | def formatColor(r, g, b):
function colorToVector (line 38) | def colorToVector(color):
function sleep (line 47) | def sleep(secs):
function begin_graphics (line 56) | def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), ti...
function _leftclick (line 101) | def _leftclick(event):
function _rightclick (line 105) | def _rightclick(event):
function _ctrl_leftclick (line 109) | def _ctrl_leftclick(event):
function wait_for_click (line 113) | def wait_for_click():
function draw_background (line 132) | def draw_background():
function _destroy_window (line 136) | def _destroy_window(event=None):
function end_graphics (line 143) | def end_graphics():
function clear_screen (line 158) | def clear_screen(background=None):
function polygon (line 164) | def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, ...
function square (line 176) | def square(pos, r, color, filled=1, behind=0):
function circle (line 181) | def circle(pos, r, outlineColor, fillColor, endpoints=None, style='piesl...
function image (line 194) | def image(pos, file="../../blueghost.gif"):
function refresh (line 200) | def refresh():
function moveCircle (line 203) | def moveCircle(id, pos, r, endpoints=None):
function edit (line 220) | def edit(id, *args):
function text (line 223) | def text(pos, color, contents, font='Helvetica', size=12, style='normal'...
function changeText (line 229) | def changeText(id, newText, font=None, size=12, style='normal'):
function changeColor (line 234) | def changeColor(id, newColor):
function line (line 237) | def line(here, there, color=formatColor(0, 0, 0), width=2):
function _keypress (line 254) | def _keypress(event):
function _keyrelease (line 262) | def _keyrelease(event):
function remap_arrows (line 271) | def remap_arrows(event):
function _clear_keys (line 284) | def _clear_keys(event=None):
function keys_pressed (line 290) | def keys_pressed(d_o_e=Tkinter.tkinter.dooneevent,
function keys_waiting (line 297) | def keys_waiting():
function wait_for_keys (line 305) | def wait_for_keys():
function remove_from_screen (line 312) | def remove_from_screen(x,
function _adjust_coords (line 318) | def _adjust_coords(coord_list, x, y):
function move_to (line 324) | def move_to(object, x, y=None,
function move_by (line 346) | def move_by(object, x, y=None,
function writePostscript (line 369) | def writePostscript(filename):
FILE: Project-1/keyboardAgents.py
class KeyboardAgent (line 19) | class KeyboardAgent(Agent):
method __init__ (line 30) | def __init__( self, index = 0 ):
method getAction (line 36) | def getAction( self, state):
method getMove (line 59) | def getMove(self, legal):
class KeyboardAgent2 (line 67) | class KeyboardAgent2(KeyboardAgent):
method getMove (line 78) | def getMove(self, legal):
FILE: Project-1/layout.py
class Layout (line 22) | class Layout:
method __init__ (line 27) | def __init__(self, layoutText):
method getNumGhosts (line 40) | def getNumGhosts(self):
method initializeVisibilityMatrix (line 43) | def initializeVisibilityMatrix(self):
method isWall (line 64) | def isWall(self, pos):
method getRandomLegalPosition (line 68) | def getRandomLegalPosition(self):
method getRandomCorner (line 76) | def getRandomCorner(self):
method getFurthestCorner (line 80) | def getFurthestCorner(self, pacPos):
method isVisibleFrom (line 85) | def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
method __str__ (line 89) | def __str__(self):
method deepCopy (line 92) | def deepCopy(self):
method processLayoutText (line 95) | def processLayoutText(self, layoutText):
method processLayoutChar (line 116) | def processLayoutChar(self, x, y, layoutChar):
function getLayout (line 131) | def getLayout(name, back = 2):
function tryToLoad (line 145) | def tryToLoad(fullname):
FILE: Project-1/pacman.py
class GameState (line 55) | class GameState:
method getAndResetExplored (line 76) | def getAndResetExplored():
method getLegalActions (line 82) | def getLegalActions( self, agentIndex=0 ):
method generateSuccessor (line 94) | def generateSuccessor( self, agentIndex, action):
method getLegalPacmanActions (line 127) | def getLegalPacmanActions( self ):
method generatePacmanSuccessor (line 130) | def generatePacmanSuccessor( self, action ):
method getPacmanState (line 136) | def getPacmanState( self ):
method getPacmanPosition (line 145) | def getPacmanPosition( self ):
method getGhostStates (line 148) | def getGhostStates( self ):
method getGhostState (line 151) | def getGhostState( self, agentIndex ):
method getGhostPosition (line 156) | def getGhostPosition( self, agentIndex ):
method getGhostPositions (line 161) | def getGhostPositions(self):
method getNumAgents (line 164) | def getNumAgents( self ):
method getScore (line 167) | def getScore( self ):
method getCapsules (line 170) | def getCapsules(self):
method getNumFood (line 176) | def getNumFood( self ):
method getFood (line 179) | def getFood(self):
method getWalls (line 191) | def getWalls(self):
method hasFood (line 203) | def hasFood(self, x, y):
method hasWall (line 206) | def hasWall(self, x, y):
method isLose (line 209) | def isLose( self ):
method isWin (line 212) | def isWin( self ):
method __init__ (line 220) | def __init__( self, prevState = None ):
method deepCopy (line 229) | def deepCopy( self ):
method __eq__ (line 234) | def __eq__( self, other ):
method __hash__ (line 240) | def __hash__( self ):
method __str__ (line 246) | def __str__( self ):
method initialize (line 250) | def initialize( self, layout, numGhostAgents=1000 ):
class ClassicGameRules (line 266) | class ClassicGameRules:
method __init__ (line 271) | def __init__(self, timeout=30):
method newGame (line 274) | def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = ...
method process (line 284) | def process(self, state, game):
method win (line 291) | def win( self, state, game ):
method lose (line 295) | def lose( self, state, game ):
method getProgress (line 299) | def getProgress(self, game):
method agentCrash (line 302) | def agentCrash(self, game, agentIndex):
method getMaxTotalTime (line 308) | def getMaxTotalTime(self, agentIndex):
method getMaxStartupTime (line 311) | def getMaxStartupTime(self, agentIndex):
method getMoveWarningTime (line 314) | def getMoveWarningTime(self, agentIndex):
method getMoveTimeout (line 317) | def getMoveTimeout(self, agentIndex):
method getMaxTimeWarnings (line 320) | def getMaxTimeWarnings(self, agentIndex):
class PacmanRules (line 323) | class PacmanRules:
method getLegalActions (line 330) | def getLegalActions( state ):
method applyAction (line 337) | def applyAction( state, action ):
method consume (line 359) | def consume( position, state ):
class GhostRules (line 381) | class GhostRules:
method getLegalActions (line 386) | def getLegalActions( state, ghostIndex ):
method applyAction (line 401) | def applyAction( state, action, ghostIndex):
method decrementTimer (line 414) | def decrementTimer( ghostState):
method checkDeath (line 421) | def checkDeath( state, agentIndex):
method collide (line 436) | def collide( state, ghostState, agentIndex):
method canKill (line 449) | def canKill( pacmanPosition, ghostPosition ):
method placeGhost (line 453) | def placeGhost(state, ghostState):
function default (line 461) | def default(str):
function parseAgentArgs (line 464) | def parseAgentArgs(str):
function readCommand (line 476) | def readCommand( argv ):
function loadAgent (line 587) | def loadAgent(pacman, nographics):
function replayGame (line 610) | def replayGame( layout, actions, display ):
function runGames (line 628) | def runGames( layout, pacman, ghosts, display, numGames, record, numTrai...
FILE: Project-1/pacmanAgents.py
class LeftTurnAgent (line 21) | class LeftTurnAgent(game.Agent):
method getAction (line 24) | def getAction(self, state):
class GreedyAgent (line 35) | class GreedyAgent(Agent):
method __init__ (line 36) | def __init__(self, evalFn="scoreEvaluation"):
method getAction (line 40) | def getAction(self, state):
function scoreEvaluation (line 51) | def scoreEvaluation(state):
FILE: Project-1/search.py
class SearchProblem (line 22) | class SearchProblem:
method getStartState (line 30) | def getStartState(self):
method isGoalState (line 36) | def isGoalState(self, state):
method getSuccessors (line 44) | def getSuccessors(self, state):
method getCostOfActions (line 55) | def getCostOfActions(self, actions):
class Path (line 64) | class Path(object):
method __init__ (line 65) | def __init__(self, locations, directions, cost):
function tinyMazeSearch (line 70) | def tinyMazeSearch(problem):
function depthFirstSearch (line 80) | def depthFirstSearch(problem):
function breadthFirstSearch (line 113) | def breadthFirstSearch(problem):
function uniformCostSearch (line 149) | def uniformCostSearch(problem):
function nullHeuristic (line 185) | def nullHeuristic(state, problem=None):
function aStarSearch (line 192) | def aStarSearch(problem, heuristic=nullHeuristic):
FILE: Project-1/searchAgents.py
class GoWestAgent (line 44) | class GoWestAgent(Agent):
method getAction (line 47) | def getAction(self, state):
class SearchAgent (line 59) | class SearchAgent(Agent):
method __init__ (line 76) | def __init__(self, fn='depthFirstSearch', prob='PositionSearchProblem'...
method registerInitialState (line 103) | def registerInitialState(self, state):
method getAction (line 120) | def getAction(self, state):
class PositionSearchProblem (line 136) | class PositionSearchProblem(search.SearchProblem):
method __init__ (line 147) | def __init__(self, gameState, costFn = lambda x: 1, goal=(1,1), start=...
method getStartState (line 167) | def getStartState(self):
method isGoalState (line 170) | def isGoalState(self, state):
method getSuccessors (line 183) | def getSuccessors(self, state):
method getCostOfActions (line 213) | def getCostOfActions(self, actions):
class StayEastSearchAgent (line 229) | class StayEastSearchAgent(SearchAgent):
method __init__ (line 236) | def __init__(self):
class StayWestSearchAgent (line 241) | class StayWestSearchAgent(SearchAgent):
method __init__ (line 248) | def __init__(self):
function manhattanHeuristic (line 253) | def manhattanHeuristic(position, problem, info={}):
function euclideanHeuristic (line 259) | def euclideanHeuristic(position, problem, info={}):
class CornersProblem (line 269) | class CornersProblem(search.SearchProblem):
method __init__ (line 276) | def __init__(self, startingGameState):
method getStartState (line 291) | def getStartState(self):
method isGoalState (line 298) | def isGoalState(self, state):
method getSuccessors (line 305) | def getSuccessors(self, state):
method getCostOfActions (line 331) | def getCostOfActions(self, actions):
function cornersHeuristic (line 345) | def cornersHeuristic(state, problem):
class AStarCornersAgent (line 378) | class AStarCornersAgent(SearchAgent):
method __init__ (line 380) | def __init__(self):
class FoodSearchProblem (line 384) | class FoodSearchProblem:
method __init__ (line 393) | def __init__(self, startingGameState):
method getStartState (line 400) | def getStartState(self):
method isGoalState (line 403) | def isGoalState(self, state):
method getSuccessors (line 406) | def getSuccessors(self, state):
method getCostOfActions (line 420) | def getCostOfActions(self, actions):
class AStarFoodSearchAgent (line 434) | class AStarFoodSearchAgent(SearchAgent):
method __init__ (line 436) | def __init__(self):
function foodHeuristic (line 440) | def foodHeuristic(state, problem):
class ClosestDotSearchAgent (line 490) | class ClosestDotSearchAgent(SearchAgent):
method registerInitialState (line 492) | def registerInitialState(self, state):
method findPathToClosestDot (line 507) | def findPathToClosestDot(self, gameState):
class AnyFoodSearchProblem (line 520) | class AnyFoodSearchProblem(PositionSearchProblem):
method __init__ (line 535) | def __init__(self, gameState):
method isGoalState (line 546) | def isGoalState(self, state):
function mazeDistance (line 554) | def mazeDistance(point1, point2, gameState):
FILE: Project-1/searchTestClasses.py
function wrap_solution (line 25) | def wrap_solution(solution):
function followAction (line 34) | def followAction(state, action, problem):
function followPath (line 39) | def followPath(path, problem):
function checkSolution (line 47) | def checkSolution(problem, path):
class GraphSearch (line 54) | class GraphSearch(SearchProblem):
method __init__ (line 57) | def __init__(self, graph_text):
method getStartState (line 98) | def getStartState(self):
method isGoalState (line 102) | def isGoalState(self, state):
method getSuccessors (line 106) | def getSuccessors(self, state):
method getCostOfActions (line 111) | def getCostOfActions(self, actions):
method getExpandedStates (line 128) | def getExpandedStates(self):
method __str__ (line 131) | def __str__(self):
function parseHeuristic (line 141) | def parseHeuristic(heuristicText):
class GraphSearchTest (line 164) | class GraphSearchTest(testClasses.TestCase):
method __init__ (line 166) | def __init__(self, question, testDict):
method getSolInfo (line 179) | def getSolInfo(self, search):
method execute (line 195) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 226) | def writeSolution(self, moduleDict, filePath):
class PacmanSearchTest (line 255) | class PacmanSearchTest(testClasses.TestCase):
method __init__ (line 257) | def __init__(self, question, testDict):
method getSolInfo (line 270) | def getSolInfo(self, search, searchAgents):
method execute (line 299) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 340) | def writeSolution(self, moduleDict, filePath):
function getStatesFromPath (line 370) | def getStatesFromPath(start, path):
class CornerProblemTest (line 381) | class CornerProblemTest(testClasses.TestCase):
method __init__ (line 383) | def __init__(self, question, testDict):
method solution (line 388) | def solution(self, search, searchAgents):
method execute (line 403) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 432) | def writeSolution(self, moduleDict, filePath):
class HeuristicTest (line 467) | class HeuristicTest(testClasses.TestCase):
method __init__ (line 469) | def __init__(self, question, testDict):
method setupProblem (line 476) | def setupProblem(self, searchAgents):
method checkHeuristic (line 487) | def checkHeuristic(self, heuristic, problem, state, solutionCost):
method execute (line 510) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 526) | def writeSolution(self, moduleDict, filePath):
class HeuristicGrade (line 549) | class HeuristicGrade(testClasses.TestCase):
method __init__ (line 551) | def __init__(self, question, testDict):
method setupProblem (line 560) | def setupProblem(self, searchAgents):
method execute (line 572) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 603) | def writeSolution(self, moduleDict, filePath):
class ClosestDotTest (line 627) | class ClosestDotTest(testClasses.TestCase):
method __init__ (line 629) | def __init__(self, question, testDict):
method solution (line 634) | def solution(self, searchAgents):
method execute (line 641) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 665) | def writeSolution(self, moduleDict, filePath):
class CornerHeuristicSanity (line 685) | class CornerHeuristicSanity(testClasses.TestCase):
method __init__ (line 687) | def __init__(self, question, testDict):
method execute (line 691) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 740) | def writeSolution(self, moduleDict, filePath):
class CornerHeuristicPacman (line 762) | class CornerHeuristicPacman(testClasses.TestCase):
method __init__ (line 764) | def __init__(self, question, testDict):
method execute (line 768) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 801) | def writeSolution(self, moduleDict, filePath):
FILE: Project-1/testClasses.py
class Question (line 24) | class Question(object):
method raiseNotDefined (line 26) | def raiseNotDefined(self):
method __init__ (line 30) | def __init__(self, questionDict, display):
method getDisplay (line 35) | def getDisplay(self):
method getMaxPoints (line 38) | def getMaxPoints(self):
method addTestCase (line 43) | def addTestCase(self, testCase, thunk):
method execute (line 46) | def execute(self, grades):
class PassAllTestsQuestion (line 50) | class PassAllTestsQuestion(Question):
method execute (line 52) | def execute(self, grades):
class HackedPartialCreditQuestion (line 67) | class HackedPartialCreditQuestion(Question):
method execute (line 69) | def execute(self, grades):
class Q6PartialCreditQuestion (line 89) | class Q6PartialCreditQuestion(Question):
method execute (line 93) | def execute(self, grades):
class PartialCreditQuestion (line 102) | class PartialCreditQuestion(Question):
method execute (line 106) | def execute(self, grades):
class NumberPassedQuestion (line 117) | class NumberPassedQuestion(Question):
method execute (line 120) | def execute(self, grades):
class TestCase (line 128) | class TestCase(object):
method raiseNotDefined (line 130) | def raiseNotDefined(self):
method getPath (line 134) | def getPath(self):
method __init__ (line 137) | def __init__(self, question, testDict):
method __str__ (line 143) | def __str__(self):
method execute (line 146) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 149) | def writeSolution(self, moduleDict, filePath):
method testPass (line 159) | def testPass(self, grades):
method testFail (line 165) | def testFail(self, grades):
method testPartial (line 173) | def testPartial(self, grades, points, maxPoints):
method addMessage (line 187) | def addMessage(self, message):
FILE: Project-1/testParser.py
class TestParser (line 18) | class TestParser(object):
method __init__ (line 20) | def __init__(self, path):
method removeComments (line 24) | def removeComments(self, rawlines):
method parse (line 35) | def parse(self):
function emitTestDict (line 76) | def emitTestDict(testDict, handle):
FILE: Project-1/textDisplay.py
class NullGraphics (line 26) | class NullGraphics:
method initialize (line 27) | def initialize(self, state, isBlue = False):
method update (line 30) | def update(self, state):
method checkNullDisplay (line 33) | def checkNullDisplay(self):
method pause (line 36) | def pause(self):
method draw (line 39) | def draw(self, state):
method updateDistributions (line 42) | def updateDistributions(self, dist):
method finish (line 45) | def finish(self):
class PacmanGraphics (line 48) | class PacmanGraphics:
method __init__ (line 49) | def __init__(self, speed=None):
method initialize (line 54) | def initialize(self, state, isBlue = False):
method update (line 60) | def update(self, state):
method pause (line 74) | def pause(self):
method draw (line 77) | def draw(self, state):
method finish (line 80) | def finish(self):
FILE: Project-1/util.py
class FixedRandom (line 21) | class FixedRandom:
method __init__ (line 22) | def __init__(self):
class Stack (line 120) | class Stack:
method __init__ (line 122) | def __init__(self):
method push (line 125) | def push(self,item):
method pop (line 129) | def pop(self):
method isEmpty (line 133) | def isEmpty(self):
class Queue (line 137) | class Queue:
method __init__ (line 139) | def __init__(self):
method push (line 142) | def push(self,item):
method pop (line 146) | def pop(self):
method isEmpty (line 153) | def isEmpty(self):
class PriorityQueue (line 157) | class PriorityQueue:
method __init__ (line 168) | def __init__(self):
method push (line 172) | def push(self, item, priority):
method pop (line 180) | def pop(self):
method isEmpty (line 185) | def isEmpty(self):
class PriorityQueueWithFunction (line 188) | class PriorityQueueWithFunction(PriorityQueue):
method __init__ (line 195) | def __init__(self, priorityFunction):
method push (line 200) | def push(self, item):
function manhattanDistance (line 205) | def manhattanDistance( xy1, xy2 ):
class Counter (line 215) | class Counter(dict):
method __getitem__ (line 255) | def __getitem__(self, idx):
method incrementAll (line 259) | def incrementAll(self, keys, count):
method argMax (line 273) | def argMax(self):
method sortedKeys (line 283) | def sortedKeys(self):
method totalCount (line 300) | def totalCount(self):
method normalize (line 306) | def normalize(self):
method divideAll (line 318) | def divideAll(self, divisor):
method copy (line 326) | def copy(self):
method __mul__ (line 332) | def __mul__(self, y ):
method __radd__ (line 358) | def __radd__(self, y):
method __add__ (line 376) | def __add__( self, y ):
method __sub__ (line 402) | def __sub__( self, y ):
function raiseNotDefined (line 428) | def raiseNotDefined():
function normalize (line 436) | def normalize(vectorOrCounter):
function nSample (line 455) | def nSample(distribution, values, n):
function sample (line 471) | def sample(distribution, values = None):
function sampleFromCounter (line 485) | def sampleFromCounter(ctr):
function getProbability (line 489) | def getProbability(value, distribution, values):
function flipCoin (line 500) | def flipCoin( p ):
function chooseFromDistribution (line 504) | def chooseFromDistribution( distribution ):
function nearestPoint (line 514) | def nearestPoint( pos ):
function sign (line 524) | def sign( x ):
function arrayInvert (line 533) | def arrayInvert(array):
function matrixAsList (line 543) | def matrixAsList( matrix, value = True ):
function lookup (line 555) | def lookup(name, namespace):
function pause (line 573) | def pause():
class TimeoutFunctionException (line 591) | class TimeoutFunctionException(Exception):
class TimeoutFunction (line 596) | class TimeoutFunction:
method __init__ (line 597) | def __init__(self, function, timeout):
method handle_timeout (line 601) | def handle_timeout(self, signum, frame):
method __call__ (line 604) | def __call__(self, *args, **keyArgs):
class WritableNull (line 630) | class WritableNull:
method write (line 631) | def write(self, string):
function mutePrint (line 634) | def mutePrint():
function unmutePrint (line 645) | def unmutePrint():
FILE: Project-2/autograder.py
function readCommand (line 31) | def readCommand(argv):
function confirmGenerate (line 83) | def confirmGenerate():
function setModuleName (line 100) | def setModuleName(module, filename):
function loadModuleString (line 118) | def loadModuleString(moduleSource):
function loadModuleFile (line 131) | def loadModuleFile(moduleName, filePath):
function readFile (line 136) | def readFile(path, root=""):
function splitStrings (line 173) | def splitStrings(d):
function printTest (line 184) | def printTest(testDict, solutionDict):
function runTest (line 194) | def runTest(testName, moduleDict, printTestCase=False, display=None):
function getDepends (line 219) | def getDepends(testParser, testRoot, question):
function getTestSubdirs (line 230) | def getTestSubdirs(testParser, testRoot, questionToGrade):
function evaluate (line 243) | def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR...
function getDisplay (line 310) | def getDisplay(graphicsByDefault, options=None):
FILE: Project-2/game.py
class Agent (line 32) | class Agent:
method __init__ (line 39) | def __init__(self, index=0):
method getAction (line 42) | def getAction(self, state):
class Directions (line 49) | class Directions:
class Configuration (line 70) | class Configuration:
method __init__ (line 79) | def __init__(self, pos, direction):
method getPosition (line 83) | def getPosition(self):
method getDirection (line 86) | def getDirection(self):
method isInteger (line 89) | def isInteger(self):
method __eq__ (line 93) | def __eq__(self, other):
method __hash__ (line 97) | def __hash__(self):
method __str__ (line 102) | def __str__(self):
method generateSuccessor (line 105) | def generateSuccessor(self, vector):
class AgentState (line 120) | class AgentState:
method __init__ (line 125) | def __init__( self, startConfiguration, isPacman ):
method __str__ (line 133) | def __str__( self ):
method __eq__ (line 139) | def __eq__( self, other ):
method __hash__ (line 144) | def __hash__(self):
method copy (line 147) | def copy( self ):
method getPosition (line 155) | def getPosition(self):
method getDirection (line 159) | def getDirection(self):
class Grid (line 162) | class Grid:
method __init__ (line 170) | def __init__(self, width, height, initialValue=False, bitRepresentatio...
method __getitem__ (line 180) | def __getitem__(self, i):
method __setitem__ (line 183) | def __setitem__(self, key, item):
method __str__ (line 186) | def __str__(self):
method __eq__ (line 191) | def __eq__(self, other):
method __hash__ (line 195) | def __hash__(self):
method copy (line 206) | def copy(self):
method deepCopy (line 211) | def deepCopy(self):
method shallowCopy (line 214) | def shallowCopy(self):
method count (line 219) | def count(self, item =True ):
method asList (line 222) | def asList(self, key = True):
method packBits (line 229) | def packBits(self):
method _cellIndexToPosition (line 248) | def _cellIndexToPosition(self, index):
method _unpackBits (line 253) | def _unpackBits(self, bits):
method _unpackInt (line 265) | def _unpackInt(self, packed, size):
function reconstituteGrid (line 277) | def reconstituteGrid(bitRep):
class Actions (line 287) | class Actions:
method reverseDirection (line 302) | def reverseDirection(action):
method vectorToDirection (line 314) | def vectorToDirection(vector):
method directionToVector (line 327) | def directionToVector(direction, speed = 1.0):
method getPossibleActions (line 332) | def getPossibleActions(config, walls):
method getLegalNeighbors (line 351) | def getLegalNeighbors(position, walls):
method getSuccessor (line 365) | def getSuccessor(position, action):
class GameStateData (line 371) | class GameStateData:
method __init__ (line 375) | def __init__( self, prevState = None ):
method deepCopy (line 395) | def deepCopy( self ):
method copyAgentStates (line 405) | def copyAgentStates( self, agentStates ):
method __eq__ (line 411) | def __eq__( self, other ):
method __hash__ (line 423) | def __hash__( self ):
method __str__ (line 435) | def __str__( self ):
method _foodWallStr (line 460) | def _foodWallStr( self, hasFood, hasWall ):
method _pacStr (line 468) | def _pacStr( self, dir ):
method _ghostStr (line 477) | def _ghostStr( self, dir ):
method initialize (line 487) | def initialize( self, layout, numGhostAgents ):
class Game (line 513) | class Game:
method __init__ (line 518) | def __init__( self, agents, display, rules, startingIndex=0, muteAgent...
method getProgress (line 534) | def getProgress(self):
method _agentCrash (line 540) | def _agentCrash( self, agentIndex, quiet=False):
method mute (line 550) | def mute(self, agentIndex):
method unmute (line 559) | def unmute(self):
method run (line 567) | def run( self ):
FILE: Project-2/ghostAgents.py
class GhostAgent (line 22) | class GhostAgent( Agent ):
method __init__ (line 23) | def __init__( self, index ):
method getAction (line 26) | def getAction( self, state ):
method getDistribution (line 33) | def getDistribution(self, state):
class RandomGhost (line 37) | class RandomGhost( GhostAgent ):
method getDistribution (line 39) | def getDistribution( self, state ):
class DirectionalGhost (line 45) | class DirectionalGhost( GhostAgent ):
method __init__ (line 47) | def __init__( self, index, prob_attack=0.8, prob_scaredFlee=0.8 ):
method getDistribution (line 52) | def getDistribution( self, state ):
FILE: Project-2/grading.py
class Grades (line 25) | class Grades:
method __init__ (line 27) | def __init__(self, projectName, questionsAndMaxesList, edxOutput=False...
method addPrereq (line 48) | def addPrereq(self, question, prereq):
method grade (line 51) | def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
method addExceptionMessage (line 139) | def addExceptionMessage(self, q, inst, traceback):
method addErrorHints (line 149) | def addErrorHints(self, exceptionMap, errorInstance, questionNum):
method produceOutput (line 171) | def produceOutput(self):
method fail (line 227) | def fail(self, message, raw=False):
method assignZeroCredit (line 233) | def assignZeroCredit(self):
method addPoints (line 236) | def addPoints(self, amt):
method deductPoints (line 239) | def deductPoints(self, amt):
method assignFullCredit (line 242) | def assignFullCredit(self, message="", raw=False):
method addMessage (line 247) | def addMessage(self, message, raw=False):
method addMessageToEmail (line 256) | def addMessageToEmail(self, message):
class Counter (line 267) | class Counter(dict):
method __getitem__ (line 271) | def __getitem__(self, idx):
method totalCount (line 277) | def totalCount(self):
FILE: Project-2/graphicsDisplay.py
class InfoPane (line 82) | class InfoPane:
method __init__ (line 83) | def __init__(self, layout, gridSize):
method toScreen (line 92) | def toScreen(self, pos, y = None):
method drawPane (line 105) | def drawPane(self):
method initializeGhostDistances (line 108) | def initializeGhostDistances(self, distances):
method updateScore (line 121) | def updateScore(self, score):
method setTeam (line 124) | def setTeam(self, isBlue):
method updateGhostDistances (line 129) | def updateGhostDistances(self, distances):
method drawGhost (line 136) | def drawGhost(self):
method drawPacman (line 139) | def drawPacman(self):
method drawWarning (line 142) | def drawWarning(self):
method clearIcon (line 145) | def clearIcon(self):
method updateMessage (line 148) | def updateMessage(self, message):
method clearMessage (line 151) | def clearMessage(self):
class PacmanGraphics (line 155) | class PacmanGraphics:
method __init__ (line 156) | def __init__(self, zoom=1.0, frameTime=0.0, capture=False):
method checkNullDisplay (line 165) | def checkNullDisplay(self):
method initialize (line 168) | def initialize(self, state, isBlue = False):
method startGraphics (line 180) | def startGraphics(self, state):
method drawDistributions (line 189) | def drawDistributions(self, state):
method drawStaticObjects (line 204) | def drawStaticObjects(self, state):
method drawAgentObjects (line 211) | def drawAgentObjects(self, state):
method swapImages (line 222) | def swapImages(self, agentIndex, newState):
method update (line 236) | def update(self, newState):
method make_window (line 256) | def make_window(self, width, height):
method drawPacman (line 267) | def drawPacman(self, pacman, index):
method getEndpoints (line 286) | def getEndpoints(self, direction, position=(0,0)):
method movePacman (line 302) | def movePacman(self, position, direction, image):
method animatePacman (line 309) | def animatePacman(self, pacman, prevPacman, image):
method getGhostColor (line 329) | def getGhostColor(self, ghost, ghostIndex):
method drawGhost (line 335) | def drawGhost(self, ghost, agentIndex):
method moveEyes (line 371) | def moveEyes(self, pos, dir, eyes):
method moveGhost (line 388) | def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
method getPosition (line 405) | def getPosition(self, agentState):
method getDirection (line 409) | def getDirection(self, agentState):
method finish (line 413) | def finish(self):
method to_screen (line 416) | def to_screen(self, point):
method to_screen2 (line 424) | def to_screen2(self, point):
method drawWalls (line 431) | def drawWalls(self, wallMatrix):
method isWall (line 517) | def isWall(self, x, y, walls):
method drawFood (line 524) | def drawFood(self, foodMatrix ):
method drawCapsules (line 544) | def drawCapsules(self, capsules ):
method removeFood (line 556) | def removeFood(self, cell, foodImages ):
method removeCapsule (line 560) | def removeCapsule(self, cell, capsuleImages ):
method drawExpandedCells (line 564) | def drawExpandedCells(self, cells):
method clearExpandedCells (line 583) | def clearExpandedCells(self):
method updateDistributions (line 589) | def updateDistributions(self, distributions):
class FirstPersonPacmanGraphics (line 611) | class FirstPersonPacmanGraphics(PacmanGraphics):
method __init__ (line 612) | def __init__(self, zoom = 1.0, showGhosts = True, capture = False, fra...
method initialize (line 617) | def initialize(self, state, isBlue = False):
method lookAhead (line 634) | def lookAhead(self, config, state):
method getGhostColor (line 648) | def getGhostColor(self, ghost, ghostIndex):
method getPosition (line 651) | def getPosition(self, ghostState):
function add (line 657) | def add(x, y):
function saveFrame (line 672) | def saveFrame():
FILE: Project-2/graphicsUtils.py
function formatColor (line 35) | def formatColor(r, g, b):
function colorToVector (line 38) | def colorToVector(color):
function sleep (line 47) | def sleep(secs):
function begin_graphics (line 56) | def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), ti...
function _leftclick (line 101) | def _leftclick(event):
function _rightclick (line 105) | def _rightclick(event):
function _ctrl_leftclick (line 109) | def _ctrl_leftclick(event):
function wait_for_click (line 113) | def wait_for_click():
function draw_background (line 132) | def draw_background():
function _destroy_window (line 136) | def _destroy_window(event=None):
function end_graphics (line 143) | def end_graphics():
function clear_screen (line 158) | def clear_screen(background=None):
function polygon (line 164) | def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, ...
function square (line 176) | def square(pos, r, color, filled=1, behind=0):
function circle (line 181) | def circle(pos, r, outlineColor, fillColor, endpoints=None, style='piesl...
function image (line 194) | def image(pos, file="../../blueghost.gif"):
function refresh (line 200) | def refresh():
function moveCircle (line 203) | def moveCircle(id, pos, r, endpoints=None):
function edit (line 220) | def edit(id, *args):
function text (line 223) | def text(pos, color, contents, font='Helvetica', size=12, style='normal'...
function changeText (line 229) | def changeText(id, newText, font=None, size=12, style='normal'):
function changeColor (line 234) | def changeColor(id, newColor):
function line (line 237) | def line(here, there, color=formatColor(0, 0, 0), width=2):
function _keypress (line 254) | def _keypress(event):
function _keyrelease (line 262) | def _keyrelease(event):
function remap_arrows (line 271) | def remap_arrows(event):
function _clear_keys (line 284) | def _clear_keys(event=None):
function keys_pressed (line 290) | def keys_pressed(d_o_e=Tkinter.tkinter.dooneevent,
function keys_waiting (line 297) | def keys_waiting():
function wait_for_keys (line 305) | def wait_for_keys():
function remove_from_screen (line 312) | def remove_from_screen(x,
function _adjust_coords (line 318) | def _adjust_coords(coord_list, x, y):
function move_to (line 324) | def move_to(object, x, y=None,
function move_by (line 346) | def move_by(object, x, y=None,
function writePostscript (line 369) | def writePostscript(filename):
FILE: Project-2/keyboardAgents.py
class KeyboardAgent (line 19) | class KeyboardAgent(Agent):
method __init__ (line 30) | def __init__( self, index = 0 ):
method getAction (line 36) | def getAction( self, state):
method getMove (line 59) | def getMove(self, legal):
class KeyboardAgent2 (line 67) | class KeyboardAgent2(KeyboardAgent):
method getMove (line 78) | def getMove(self, legal):
FILE: Project-2/layout.py
class Layout (line 22) | class Layout:
method __init__ (line 27) | def __init__(self, layoutText):
method getNumGhosts (line 40) | def getNumGhosts(self):
method initializeVisibilityMatrix (line 43) | def initializeVisibilityMatrix(self):
method isWall (line 64) | def isWall(self, pos):
method getRandomLegalPosition (line 68) | def getRandomLegalPosition(self):
method getRandomCorner (line 76) | def getRandomCorner(self):
method getFurthestCorner (line 80) | def getFurthestCorner(self, pacPos):
method isVisibleFrom (line 85) | def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
method __str__ (line 89) | def __str__(self):
method deepCopy (line 92) | def deepCopy(self):
method processLayoutText (line 95) | def processLayoutText(self, layoutText):
method processLayoutChar (line 116) | def processLayoutChar(self, x, y, layoutChar):
function getLayout (line 131) | def getLayout(name, back = 2):
function tryToLoad (line 145) | def tryToLoad(fullname):
FILE: Project-2/multiAgents.py
class ReflexAgent (line 21) | class ReflexAgent(Agent):
method getAction (line 32) | def getAction(self, gameState):
method evaluationFunction (line 54) | def evaluationFunction(self, currentGameState, action):
function scoreEvaluationFunction (line 93) | def scoreEvaluationFunction(currentGameState):
class MultiAgentSearchAgent (line 103) | class MultiAgentSearchAgent(Agent):
method __init__ (line 118) | def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
class MinimaxAgent (line 123) | class MinimaxAgent(MultiAgentSearchAgent):
method getAction (line 128) | def getAction(self, gameState):
method getValue (line 156) | def getValue(self, gameState, currentDepth, agentIndex):
method maxValue (line 164) | def maxValue(self, gameState, currentDepth):
method minValue (line 170) | def minValue(self, gameState, currentDepth, agentIndex):
class AlphaBetaAgent (line 179) | class AlphaBetaAgent(MultiAgentSearchAgent):
method getAction (line 184) | def getAction(self, gameState):
method getValue (line 202) | def getValue(self, gameState, currentDepth, agentIndex, alpha, beta):
method maxValue (line 210) | def maxValue(self, gameState, currentDepth, alpha, beta):
method minValue (line 219) | def minValue(self, gameState, currentDepth, agentIndex, alpha, beta):
class ExpectimaxAgent (line 231) | class ExpectimaxAgent(MultiAgentSearchAgent):
method getAction (line 236) | def getAction(self, gameState):
method getValue (line 253) | def getValue(self, gameState, currentDepth, agentIndex):
method maxValue (line 261) | def maxValue(self, gameState, currentDepth):
method avgValue (line 267) | def avgValue(self, gameState, currentDepth, agentIndex):
function betterEvaluationFunction (line 276) | def betterEvaluationFunction(currentGameState):
FILE: Project-2/multiagentTestClasses.py
class MultiagentTreeState (line 40) | class MultiagentTreeState(object):
method __init__ (line 41) | def __init__(self, problem, state):
method generateSuccessor (line 45) | def generateSuccessor(self, agentIndex, action):
method getScore (line 52) | def getScore(self):
method getLegalActions (line 59) | def getLegalActions(self, agentIndex=0):
method isWin (line 66) | def isWin(self):
method isLose (line 71) | def isLose(self):
method getNumAgents (line 76) | def getNumAgents(self):
class MultiagentTreeProblem (line 82) | class MultiagentTreeProblem(object):
method __init__ (line 83) | def __init__(self, numAgents, startState, winStates, loseStates, succe...
method reset (line 100) | def reset(self):
function parseTreeProblem (line 104) | def parseTreeProblem(testDict):
function run (line 132) | def run(lay, layName, pac, ghosts, disp, nGames=1, name='games'):
class GradingAgent (line 145) | class GradingAgent(Agent):
method __init__ (line 146) | def __init__(self, seed, studentAgent, optimalActions, altDepthActions...
method registerInitialState (line 163) | def registerInitialState(self, state):
method getAction (line 168) | def getAction(self, state):
method getSuboptimalMoves (line 197) | def getSuboptimalMoves(self):
method getWrongStatesExplored (line 200) | def getWrongStatesExplored(self):
method checkFailure (line 203) | def checkFailure(self):
class PolyAgent (line 221) | class PolyAgent(Agent):
method __init__ (line 222) | def __init__(self, seed, multiAgents, ourPacOptions, depth):
method select (line 243) | def select(self, list, indices):
method construct_our_pacs (line 249) | def construct_our_pacs(self, multiAgents, keyword_dict):
method registerInitialState (line 263) | def registerInitialState(self, state):
method getAction (line 269) | def getAction(self, state):
method getTraces (line 285) | def getTraces(self):
class PacmanGameTreeTest (line 289) | class PacmanGameTreeTest(testClasses.TestCase):
method __init__ (line 291) | def __init__(self, question, testDict):
method execute (line 300) | def execute(self, grades, moduleDict, solutionDict):
method writeList (line 342) | def writeList(self, handle, name, list):
method writeSolution (line 348) | def writeSolution(self, moduleDict, filePath):
class GraphGameTreeTest (line 372) | class GraphGameTreeTest(testClasses.TestCase):
method __init__ (line 374) | def __init__(self, question, testDict):
method solveProblem (line 381) | def solveProblem(self, multiAgents):
method addDiagram (line 388) | def addDiagram(self):
method execute (line 393) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 416) | def writeSolution(self, moduleDict, filePath):
class EvalAgentTest (line 430) | class EvalAgentTest(testClasses.TestCase):
method __init__ (line 432) | def __init__(self, question, testDict):
method execute (line 453) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 520) | def writeSolution(self, moduleDict, filePath):
FILE: Project-2/pacman.py
class GameState (line 55) | class GameState:
method getAndResetExplored (line 76) | def getAndResetExplored():
method getLegalActions (line 82) | def getLegalActions( self, agentIndex=0 ):
method generateSuccessor (line 94) | def generateSuccessor( self, agentIndex, action):
method getLegalPacmanActions (line 127) | def getLegalPacmanActions( self ):
method generatePacmanSuccessor (line 130) | def generatePacmanSuccessor( self, action ):
method getPacmanState (line 136) | def getPacmanState( self ):
method getPacmanPosition (line 145) | def getPacmanPosition( self ):
method getGhostStates (line 148) | def getGhostStates( self ):
method getGhostState (line 151) | def getGhostState( self, agentIndex ):
method getGhostPosition (line 156) | def getGhostPosition( self, agentIndex ):
method getGhostPositions (line 161) | def getGhostPositions(self):
method getNumAgents (line 164) | def getNumAgents( self ):
method getScore (line 167) | def getScore( self ):
method getCapsules (line 170) | def getCapsules(self):
method getNumFood (line 176) | def getNumFood( self ):
method getFood (line 179) | def getFood(self):
method getWalls (line 191) | def getWalls(self):
method hasFood (line 203) | def hasFood(self, x, y):
method hasWall (line 206) | def hasWall(self, x, y):
method isLose (line 209) | def isLose( self ):
method isWin (line 212) | def isWin( self ):
method __init__ (line 220) | def __init__( self, prevState = None ):
method deepCopy (line 229) | def deepCopy( self ):
method __eq__ (line 234) | def __eq__( self, other ):
method __hash__ (line 240) | def __hash__( self ):
method __str__ (line 246) | def __str__( self ):
method initialize (line 250) | def initialize( self, layout, numGhostAgents=1000 ):
class ClassicGameRules (line 266) | class ClassicGameRules:
method __init__ (line 271) | def __init__(self, timeout=30):
method newGame (line 274) | def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = ...
method process (line 284) | def process(self, state, game):
method win (line 291) | def win( self, state, game ):
method lose (line 295) | def lose( self, state, game ):
method getProgress (line 299) | def getProgress(self, game):
method agentCrash (line 302) | def agentCrash(self, game, agentIndex):
method getMaxTotalTime (line 308) | def getMaxTotalTime(self, agentIndex):
method getMaxStartupTime (line 311) | def getMaxStartupTime(self, agentIndex):
method getMoveWarningTime (line 314) | def getMoveWarningTime(self, agentIndex):
method getMoveTimeout (line 317) | def getMoveTimeout(self, agentIndex):
method getMaxTimeWarnings (line 320) | def getMaxTimeWarnings(self, agentIndex):
class PacmanRules (line 323) | class PacmanRules:
method getLegalActions (line 330) | def getLegalActions( state ):
method applyAction (line 337) | def applyAction( state, action ):
method consume (line 359) | def consume( position, state ):
class GhostRules (line 381) | class GhostRules:
method getLegalActions (line 386) | def getLegalActions( state, ghostIndex ):
method applyAction (line 401) | def applyAction( state, action, ghostIndex):
method decrementTimer (line 414) | def decrementTimer( ghostState):
method checkDeath (line 421) | def checkDeath( state, agentIndex):
method collide (line 436) | def collide( state, ghostState, agentIndex):
method canKill (line 449) | def canKill( pacmanPosition, ghostPosition ):
method placeGhost (line 453) | def placeGhost(state, ghostState):
function default (line 461) | def default(str):
function parseAgentArgs (line 464) | def parseAgentArgs(str):
function readCommand (line 476) | def readCommand( argv ):
function loadAgent (line 587) | def loadAgent(pacman, nographics):
function replayGame (line 610) | def replayGame( layout, actions, display ):
function runGames (line 628) | def runGames( layout, pacman, ghosts, display, numGames, record, numTrai...
FILE: Project-2/pacmanAgents.py
class LeftTurnAgent (line 21) | class LeftTurnAgent(game.Agent):
method getAction (line 24) | def getAction(self, state):
class GreedyAgent (line 35) | class GreedyAgent(Agent):
method __init__ (line 36) | def __init__(self, evalFn="scoreEvaluation"):
method getAction (line 40) | def getAction(self, state):
function scoreEvaluation (line 51) | def scoreEvaluation(state):
FILE: Project-2/testClasses.py
class Question (line 24) | class Question(object):
method raiseNotDefined (line 26) | def raiseNotDefined(self):
method __init__ (line 30) | def __init__(self, questionDict, display):
method getDisplay (line 35) | def getDisplay(self):
method getMaxPoints (line 38) | def getMaxPoints(self):
method addTestCase (line 43) | def addTestCase(self, testCase, thunk):
method execute (line 46) | def execute(self, grades):
class PassAllTestsQuestion (line 50) | class PassAllTestsQuestion(Question):
method execute (line 52) | def execute(self, grades):
class HackedPartialCreditQuestion (line 67) | class HackedPartialCreditQuestion(Question):
method execute (line 69) | def execute(self, grades):
class Q6PartialCreditQuestion (line 89) | class Q6PartialCreditQuestion(Question):
method execute (line 93) | def execute(self, grades):
class PartialCreditQuestion (line 102) | class PartialCreditQuestion(Question):
method execute (line 106) | def execute(self, grades):
class NumberPassedQuestion (line 117) | class NumberPassedQuestion(Question):
method execute (line 120) | def execute(self, grades):
class TestCase (line 128) | class TestCase(object):
method raiseNotDefined (line 130) | def raiseNotDefined(self):
method getPath (line 134) | def getPath(self):
method __init__ (line 137) | def __init__(self, question, testDict):
method __str__ (line 143) | def __str__(self):
method execute (line 146) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 149) | def writeSolution(self, moduleDict, filePath):
method testPass (line 159) | def testPass(self, grades):
method testFail (line 165) | def testFail(self, grades):
method testPartial (line 173) | def testPartial(self, grades, points, maxPoints):
method addMessage (line 187) | def addMessage(self, message):
FILE: Project-2/testParser.py
class TestParser (line 18) | class TestParser(object):
method __init__ (line 20) | def __init__(self, path):
method removeComments (line 24) | def removeComments(self, rawlines):
method parse (line 35) | def parse(self):
function emitTestDict (line 76) | def emitTestDict(testDict, handle):
FILE: Project-2/textDisplay.py
class NullGraphics (line 26) | class NullGraphics:
method initialize (line 27) | def initialize(self, state, isBlue = False):
method update (line 30) | def update(self, state):
method checkNullDisplay (line 33) | def checkNullDisplay(self):
method pause (line 36) | def pause(self):
method draw (line 39) | def draw(self, state):
method updateDistributions (line 42) | def updateDistributions(self, dist):
method finish (line 45) | def finish(self):
class PacmanGraphics (line 48) | class PacmanGraphics:
method __init__ (line 49) | def __init__(self, speed=None):
method initialize (line 54) | def initialize(self, state, isBlue = False):
method update (line 60) | def update(self, state):
method pause (line 74) | def pause(self):
method draw (line 77) | def draw(self, state):
method finish (line 80) | def finish(self):
FILE: Project-2/util.py
class FixedRandom (line 21) | class FixedRandom:
method __init__ (line 22) | def __init__(self):
class Stack (line 120) | class Stack:
method __init__ (line 122) | def __init__(self):
method push (line 125) | def push(self,item):
method pop (line 129) | def pop(self):
method isEmpty (line 133) | def isEmpty(self):
class Queue (line 137) | class Queue:
method __init__ (line 139) | def __init__(self):
method push (line 142) | def push(self,item):
method pop (line 146) | def pop(self):
method isEmpty (line 153) | def isEmpty(self):
class PriorityQueue (line 157) | class PriorityQueue:
method __init__ (line 168) | def __init__(self):
method push (line 172) | def push(self, item, priority):
method pop (line 180) | def pop(self):
method isEmpty (line 185) | def isEmpty(self):
class PriorityQueueWithFunction (line 188) | class PriorityQueueWithFunction(PriorityQueue):
method __init__ (line 195) | def __init__(self, priorityFunction):
method push (line 200) | def push(self, item):
function manhattanDistance (line 205) | def manhattanDistance( xy1, xy2 ):
class Counter (line 215) | class Counter(dict):
method __getitem__ (line 255) | def __getitem__(self, idx):
method incrementAll (line 259) | def incrementAll(self, keys, count):
method argMax (line 273) | def argMax(self):
method sortedKeys (line 283) | def sortedKeys(self):
method totalCount (line 300) | def totalCount(self):
method normalize (line 306) | def normalize(self):
method divideAll (line 318) | def divideAll(self, divisor):
method copy (line 326) | def copy(self):
method __mul__ (line 332) | def __mul__(self, y ):
method __radd__ (line 358) | def __radd__(self, y):
method __add__ (line 376) | def __add__( self, y ):
method __sub__ (line 402) | def __sub__( self, y ):
function raiseNotDefined (line 428) | def raiseNotDefined():
function normalize (line 436) | def normalize(vectorOrCounter):
function nSample (line 455) | def nSample(distribution, values, n):
function sample (line 471) | def sample(distribution, values = None):
function sampleFromCounter (line 485) | def sampleFromCounter(ctr):
function getProbability (line 489) | def getProbability(value, distribution, values):
function flipCoin (line 500) | def flipCoin( p ):
function chooseFromDistribution (line 504) | def chooseFromDistribution( distribution ):
function nearestPoint (line 514) | def nearestPoint( pos ):
function sign (line 524) | def sign( x ):
function arrayInvert (line 533) | def arrayInvert(array):
function matrixAsList (line 543) | def matrixAsList( matrix, value = True ):
function lookup (line 555) | def lookup(name, namespace):
function pause (line 573) | def pause():
class TimeoutFunctionException (line 591) | class TimeoutFunctionException(Exception):
class TimeoutFunction (line 596) | class TimeoutFunction:
method __init__ (line 597) | def __init__(self, function, timeout):
method handle_timeout (line 601) | def handle_timeout(self, signum, frame):
method __call__ (line 604) | def __call__(self, *args, **keyArgs):
class WritableNull (line 630) | class WritableNull:
method write (line 631) | def write(self, string):
function mutePrint (line 634) | def mutePrint():
function unmutePrint (line 645) | def unmutePrint():
FILE: Project-3/analysis.py
function question2 (line 22) | def question2():
function question3a (line 27) | def question3a():
function question3b (line 33) | def question3b():
function question3c (line 39) | def question3c():
function question3d (line 45) | def question3d():
function question3e (line 51) | def question3e():
function question6 (line 57) | def question6():
FILE: Project-3/autograder.py
function readCommand (line 31) | def readCommand(argv):
function confirmGenerate (line 83) | def confirmGenerate():
function setModuleName (line 100) | def setModuleName(module, filename):
function loadModuleString (line 118) | def loadModuleString(moduleSource):
function loadModuleFile (line 131) | def loadModuleFile(moduleName, filePath):
function readFile (line 136) | def readFile(path, root=""):
function splitStrings (line 173) | def splitStrings(d):
function printTest (line 184) | def printTest(testDict, solutionDict):
function runTest (line 194) | def runTest(testName, moduleDict, printTestCase=False, display=None):
function getDepends (line 219) | def getDepends(testParser, testRoot, question):
function getTestSubdirs (line 230) | def getTestSubdirs(testParser, testRoot, questionToGrade):
function evaluate (line 243) | def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR...
function getDisplay (line 310) | def getDisplay(graphicsByDefault, options=None):
FILE: Project-3/crawler.py
class CrawlingRobotEnvironment (line 22) | class CrawlingRobotEnvironment(environment.Environment):
method __init__ (line 24) | def __init__(self, crawlingRobot):
method getCurrentState (line 50) | def getCurrentState(self):
method getPossibleActions (line 57) | def getPossibleActions(self, state):
method doAction (line 74) | def doAction(self, action):
method reset (line 117) | def reset(self):
class CrawlingRobot (line 136) | class CrawlingRobot:
method setAngles (line 138) | def setAngles(self, armAngle, handAngle):
method getAngles (line 146) | def getAngles(self):
method getRobotPosition (line 152) | def getRobotPosition(self):
method moveArm (line 160) | def moveArm(self, newArmAngle):
method moveHand (line 182) | def moveHand(self, newHandAngle):
method getMinAndMaxArmAngles (line 204) | def getMinAndMaxArmAngles(self):
method getMinAndMaxHandAngles (line 211) | def getMinAndMaxHandAngles(self):
method getRotationAngle (line 218) | def getRotationAngle(self):
method __getCosAndSin (line 235) | def __getCosAndSin(self, angle):
method displacement (line 238) | def displacement(self, oldArmDegree, oldHandDegree, armDegree, handDeg...
method draw (line 262) | def draw(self, stepCount, stepDelay):
method __init__ (line 334) | def __init__(self, canvas):
FILE: Project-3/environment.py
class Environment (line 17) | class Environment:
method getCurrentState (line 19) | def getCurrentState(self):
method getPossibleActions (line 25) | def getPossibleActions(self, state):
method doAction (line 34) | def doAction(self, action):
method reset (line 43) | def reset(self):
method isTerminal (line 49) | def isTerminal(self):
FILE: Project-3/featureExtractors.py
class FeatureExtractor (line 20) | class FeatureExtractor:
method getFeatures (line 21) | def getFeatures(self, state, action):
class IdentityExtractor (line 29) | class IdentityExtractor(FeatureExtractor):
method getFeatures (line 30) | def getFeatures(self, state, action):
class CoordinateExtractor (line 35) | class CoordinateExtractor(FeatureExtractor):
method getFeatures (line 36) | def getFeatures(self, state, action):
function closestFood (line 44) | def closestFood(pos, food, walls):
class SimpleExtractor (line 66) | class SimpleExtractor(FeatureExtractor):
method getFeatures (line 75) | def getFeatures(self, state, action):
FILE: Project-3/game.py
class Agent (line 32) | class Agent:
method __init__ (line 39) | def __init__(self, index=0):
method getAction (line 42) | def getAction(self, state):
class Directions (line 49) | class Directions:
class Configuration (line 70) | class Configuration:
method __init__ (line 79) | def __init__(self, pos, direction):
method getPosition (line 83) | def getPosition(self):
method getDirection (line 86) | def getDirection(self):
method isInteger (line 89) | def isInteger(self):
method __eq__ (line 93) | def __eq__(self, other):
method __hash__ (line 97) | def __hash__(self):
method __str__ (line 102) | def __str__(self):
method generateSuccessor (line 105) | def generateSuccessor(self, vector):
class AgentState (line 120) | class AgentState:
method __init__ (line 125) | def __init__( self, startConfiguration, isPacman ):
method __str__ (line 133) | def __str__( self ):
method __eq__ (line 139) | def __eq__( self, other ):
method __hash__ (line 144) | def __hash__(self):
method copy (line 147) | def copy( self ):
method getPosition (line 155) | def getPosition(self):
method getDirection (line 159) | def getDirection(self):
class Grid (line 162) | class Grid:
method __init__ (line 170) | def __init__(self, width, height, initialValue=False, bitRepresentatio...
method __getitem__ (line 180) | def __getitem__(self, i):
method __setitem__ (line 183) | def __setitem__(self, key, item):
method __str__ (line 186) | def __str__(self):
method __eq__ (line 191) | def __eq__(self, other):
method __hash__ (line 195) | def __hash__(self):
method copy (line 206) | def copy(self):
method deepCopy (line 211) | def deepCopy(self):
method shallowCopy (line 214) | def shallowCopy(self):
method count (line 219) | def count(self, item =True ):
method asList (line 222) | def asList(self, key = True):
method packBits (line 229) | def packBits(self):
method _cellIndexToPosition (line 248) | def _cellIndexToPosition(self, index):
method _unpackBits (line 253) | def _unpackBits(self, bits):
method _unpackInt (line 265) | def _unpackInt(self, packed, size):
function reconstituteGrid (line 277) | def reconstituteGrid(bitRep):
class Actions (line 287) | class Actions:
method reverseDirection (line 302) | def reverseDirection(action):
method vectorToDirection (line 314) | def vectorToDirection(vector):
method directionToVector (line 327) | def directionToVector(direction, speed = 1.0):
method getPossibleActions (line 332) | def getPossibleActions(config, walls):
method getLegalNeighbors (line 351) | def getLegalNeighbors(position, walls):
method getSuccessor (line 365) | def getSuccessor(position, action):
class GameStateData (line 371) | class GameStateData:
method __init__ (line 375) | def __init__( self, prevState = None ):
method deepCopy (line 395) | def deepCopy( self ):
method copyAgentStates (line 405) | def copyAgentStates( self, agentStates ):
method __eq__ (line 411) | def __eq__( self, other ):
method __hash__ (line 423) | def __hash__( self ):
method __str__ (line 435) | def __str__( self ):
method _foodWallStr (line 460) | def _foodWallStr( self, hasFood, hasWall ):
method _pacStr (line 468) | def _pacStr( self, dir ):
method _ghostStr (line 477) | def _ghostStr( self, dir ):
method initialize (line 487) | def initialize( self, layout, numGhostAgents ):
class Game (line 513) | class Game:
method __init__ (line 518) | def __init__( self, agents, display, rules, startingIndex=0, muteAgent...
method getProgress (line 534) | def getProgress(self):
method _agentCrash (line 540) | def _agentCrash( self, agentIndex, quiet=False):
method mute (line 550) | def mute(self, agentIndex):
method unmute (line 559) | def unmute(self):
method run (line 567) | def run( self ):
FILE: Project-3/ghostAgents.py
class GhostAgent (line 22) | class GhostAgent( Agent ):
method __init__ (line 23) | def __init__( self, index ):
method getAction (line 26) | def getAction( self, state ):
method getDistribution (line 33) | def getDistribution(self, state):
class RandomGhost (line 37) | class RandomGhost( GhostAgent ):
method getDistribution (line 39) | def getDistribution( self, state ):
class DirectionalGhost (line 45) | class DirectionalGhost( GhostAgent ):
method __init__ (line 47) | def __init__( self, index, prob_attack=0.8, prob_scaredFlee=0.8 ):
method getDistribution (line 52) | def getDistribution( self, state ):
FILE: Project-3/grading.py
class Grades (line 25) | class Grades:
method __init__ (line 27) | def __init__(self, projectName, questionsAndMaxesList, edxOutput=False...
method addPrereq (line 48) | def addPrereq(self, question, prereq):
method grade (line 51) | def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
method addExceptionMessage (line 139) | def addExceptionMessage(self, q, inst, traceback):
method addErrorHints (line 149) | def addErrorHints(self, exceptionMap, errorInstance, questionNum):
method produceOutput (line 171) | def produceOutput(self):
method fail (line 227) | def fail(self, message, raw=False):
method assignZeroCredit (line 233) | def assignZeroCredit(self):
method addPoints (line 236) | def addPoints(self, amt):
method deductPoints (line 239) | def deductPoints(self, amt):
method assignFullCredit (line 242) | def assignFullCredit(self, message="", raw=False):
method addMessage (line 247) | def addMessage(self, message, raw=False):
method addMessageToEmail (line 256) | def addMessageToEmail(self, message):
class Counter (line 267) | class Counter(dict):
method __getitem__ (line 271) | def __getitem__(self, idx):
method totalCount (line 277) | def totalCount(self):
FILE: Project-3/graphicsCrawlerDisplay.py
class Application (line 37) | class Application:
method sigmoid (line 39) | def sigmoid(self, x):
method incrementSpeed (line 42) | def incrementSpeed(self, inc):
method incrementEpsilon (line 49) | def incrementEpsilon(self, inc):
method incrementGamma (line 55) | def incrementGamma(self, inc):
method incrementAlpha (line 61) | def incrementAlpha(self, inc):
method __initGUI (line 67) | def __initGUI(self, win):
method setupAlphaButtonAndLabel (line 99) | def setupAlphaButtonAndLabel(self, win):
method setUpGammaButtonAndLabel (line 112) | def setUpGammaButtonAndLabel(self, win):
method setupEpsilonButtonAndLabel (line 125) | def setupEpsilonButtonAndLabel(self, win):
method setupSpeedButtonAndLabel (line 138) | def setupSpeedButtonAndLabel(self, win):
method skip5kSteps (line 156) | def skip5kSteps(self):
method __init__ (line 159) | def __init__(self, win):
method exit (line 199) | def exit(self):
method step (line 210) | def step(self):
method animatePolicy (line 227) | def animatePolicy(self):
method run (line 288) | def run(self):
method start (line 307) | def start(self):
function run (line 314) | def run():
FILE: Project-3/graphicsDisplay.py
class InfoPane (line 82) | class InfoPane:
method __init__ (line 83) | def __init__(self, layout, gridSize):
method toScreen (line 92) | def toScreen(self, pos, y = None):
method drawPane (line 105) | def drawPane(self):
method initializeGhostDistances (line 108) | def initializeGhostDistances(self, distances):
method updateScore (line 121) | def updateScore(self, score):
method setTeam (line 124) | def setTeam(self, isBlue):
method updateGhostDistances (line 129) | def updateGhostDistances(self, distances):
method drawGhost (line 136) | def drawGhost(self):
method drawPacman (line 139) | def drawPacman(self):
method drawWarning (line 142) | def drawWarning(self):
method clearIcon (line 145) | def clearIcon(self):
method updateMessage (line 148) | def updateMessage(self, message):
method clearMessage (line 151) | def clearMessage(self):
class PacmanGraphics (line 155) | class PacmanGraphics:
method __init__ (line 156) | def __init__(self, zoom=1.0, frameTime=0.0, capture=False):
method checkNullDisplay (line 165) | def checkNullDisplay(self):
method initialize (line 168) | def initialize(self, state, isBlue = False):
method startGraphics (line 180) | def startGraphics(self, state):
method drawDistributions (line 189) | def drawDistributions(self, state):
method drawStaticObjects (line 204) | def drawStaticObjects(self, state):
method drawAgentObjects (line 211) | def drawAgentObjects(self, state):
method swapImages (line 222) | def swapImages(self, agentIndex, newState):
method update (line 236) | def update(self, newState):
method make_window (line 256) | def make_window(self, width, height):
method drawPacman (line 267) | def drawPacman(self, pacman, index):
method getEndpoints (line 286) | def getEndpoints(self, direction, position=(0,0)):
method movePacman (line 302) | def movePacman(self, position, direction, image):
method animatePacman (line 309) | def animatePacman(self, pacman, prevPacman, image):
method getGhostColor (line 329) | def getGhostColor(self, ghost, ghostIndex):
method drawGhost (line 335) | def drawGhost(self, ghost, agentIndex):
method moveEyes (line 371) | def moveEyes(self, pos, dir, eyes):
method moveGhost (line 388) | def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
method getPosition (line 405) | def getPosition(self, agentState):
method getDirection (line 409) | def getDirection(self, agentState):
method finish (line 413) | def finish(self):
method to_screen (line 416) | def to_screen(self, point):
method to_screen2 (line 424) | def to_screen2(self, point):
method drawWalls (line 431) | def drawWalls(self, wallMatrix):
method isWall (line 517) | def isWall(self, x, y, walls):
method drawFood (line 524) | def drawFood(self, foodMatrix ):
method drawCapsules (line 544) | def drawCapsules(self, capsules ):
method removeFood (line 556) | def removeFood(self, cell, foodImages ):
method removeCapsule (line 560) | def removeCapsule(self, cell, capsuleImages ):
method drawExpandedCells (line 564) | def drawExpandedCells(self, cells):
method clearExpandedCells (line 583) | def clearExpandedCells(self):
method updateDistributions (line 589) | def updateDistributions(self, distributions):
class FirstPersonPacmanGraphics (line 611) | class FirstPersonPacmanGraphics(PacmanGraphics):
method __init__ (line 612) | def __init__(self, zoom = 1.0, showGhosts = True, capture = False, fra...
method initialize (line 617) | def initialize(self, state, isBlue = False):
method lookAhead (line 634) | def lookAhead(self, config, state):
method getGhostColor (line 648) | def getGhostColor(self, ghost, ghostIndex):
method getPosition (line 651) | def getPosition(self, ghostState):
function add (line 657) | def add(x, y):
function saveFrame (line 672) | def saveFrame():
FILE: Project-3/graphicsGridworldDisplay.py
class GraphicsGridworldDisplay (line 18) | class GraphicsGridworldDisplay:
method __init__ (line 20) | def __init__(self, gridworld, size=120, speed=1.0):
method start (line 25) | def start(self):
method pause (line 28) | def pause(self):
method displayValues (line 31) | def displayValues(self, agent, currentState = None, message = 'Agent V...
method displayNullValues (line 41) | def displayNullValues(self, currentState = None, message = ''):
method displayQValues (line 52) | def displayQValues(self, agent, currentState = None, message = 'Agent ...
function setup (line 73) | def setup(gridworld, title = "Gridworld Display", size = 120):
function drawNullValues (line 87) | def drawNullValues(gridworld, currentState = None, message = ''):
function drawValues (line 104) | def drawValues(gridworld, values, policy, currentState = None, message =...
function drawQValues (line 131) | def drawQValues(gridworld, qValues, currentState = None, message = 'Stat...
function blank (line 170) | def blank():
function drawNullSquare (line 173) | def drawNullSquare(grid,x, y, isObstacle, isTerminal, isCurrent):
function drawSquare (line 213) | def drawSquare(x, y, val, min, max, valStr, action, isObstacle, isTermin...
function drawSquareQ (line 258) | def drawSquareQ(x, y, qVals, minVal, maxVal, valStrs, bestActions, isCur...
function getColor (line 322) | def getColor(val, minVal, max):
function square (line 331) | def square(pos, size, color, filled, width):
function to_screen (line 337) | def to_screen(point):
function to_grid (line 343) | def to_grid(point):
FILE: Project-3/graphicsUtils.py
function formatColor (line 35) | def formatColor(r, g, b):
function colorToVector (line 38) | def colorToVector(color):
function sleep (line 47) | def sleep(secs):
function begin_graphics (line 56) | def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), ti...
function _leftclick (line 101) | def _leftclick(event):
function _rightclick (line 105) | def _rightclick(event):
function _ctrl_leftclick (line 109) | def _ctrl_leftclick(event):
function wait_for_click (line 113) | def wait_for_click():
function draw_background (line 132) | def draw_background():
function _destroy_window (line 136) | def _destroy_window(event=None):
function end_graphics (line 143) | def end_graphics():
function clear_screen (line 158) | def clear_screen(background=None):
function polygon (line 164) | def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, ...
function square (line 176) | def square(pos, r, color, filled=1, behind=0):
function circle (line 181) | def circle(pos, r, outlineColor, fillColor, endpoints=None, style='piesl...
function image (line 194) | def image(pos, file="../../blueghost.gif"):
function refresh (line 200) | def refresh():
function moveCircle (line 203) | def moveCircle(id, pos, r, endpoints=None):
function edit (line 220) | def edit(id, *args):
function text (line 223) | def text(pos, color, contents, font='Helvetica', size=12, style='normal'...
function changeText (line 229) | def changeText(id, newText, font=None, size=12, style='normal'):
function changeColor (line 234) | def changeColor(id, newColor):
function line (line 237) | def line(here, there, color=formatColor(0, 0, 0), width=2):
function _keypress (line 254) | def _keypress(event):
function _keyrelease (line 262) | def _keyrelease(event):
function remap_arrows (line 271) | def remap_arrows(event):
function _clear_keys (line 284) | def _clear_keys(event=None):
function keys_pressed (line 290) | def keys_pressed(d_o_e=Tkinter.tkinter.dooneevent,
function keys_waiting (line 297) | def keys_waiting():
function wait_for_keys (line 305) | def wait_for_keys():
function remove_from_screen (line 312) | def remove_from_screen(x,
function _adjust_coords (line 318) | def _adjust_coords(coord_list, x, y):
function move_to (line 324) | def move_to(object, x, y=None,
function move_by (line 346) | def move_by(object, x, y=None,
function writePostscript (line 369) | def writePostscript(filename):
FILE: Project-3/gridworld.py
class Gridworld (line 22) | class Gridworld(mdp.MarkovDecisionProcess):
method __init__ (line 26) | def __init__(self, grid):
method setLivingReward (line 35) | def setLivingReward(self, reward):
method setNoise (line 45) | def setNoise(self, noise):
method getPossibleActions (line 52) | def getPossibleActions(self, state):
method getStates (line 67) | def getStates(self):
method getReward (line 80) | def getReward(self, state, action, nextState):
method getStartState (line 96) | def getStartState(self):
method isTerminal (line 103) | def isTerminal(self, state):
method getTransitionStatesAndProbs (line 114) | def getTransitionStatesAndProbs(self, state, action):
method __aggregate (line 165) | def __aggregate(self, statesAndProbs):
method __isAllowed (line 174) | def __isAllowed(self, y, x):
class GridworldEnvironment (line 179) | class GridworldEnvironment(environment.Environment):
method __init__ (line 181) | def __init__(self, gridWorld):
method getCurrentState (line 185) | def getCurrentState(self):
method getPossibleActions (line 188) | def getPossibleActions(self, state):
method doAction (line 191) | def doAction(self, action):
method getRandomNextState (line 197) | def getRandomNextState(self, state, action, randObj=None):
method reset (line 214) | def reset(self):
class Grid (line 217) | class Grid:
method __init__ (line 225) | def __init__(self, width, height, initialValue=' '):
method __getitem__ (line 231) | def __getitem__(self, i):
method __setitem__ (line 234) | def __setitem__(self, key, item):
method __eq__ (line 237) | def __eq__(self, other):
method __hash__ (line 241) | def __hash__(self):
method copy (line 244) | def copy(self):
method deepCopy (line 249) | def deepCopy(self):
method shallowCopy (line 252) | def shallowCopy(self):
method _getLegacyText (line 257) | def _getLegacyText(self):
method __str__ (line 262) | def __str__(self):
function makeGrid (line 265) | def makeGrid(gridString):
function getCliffGrid (line 274) | def getCliffGrid():
function getCliffGrid2 (line 280) | def getCliffGrid2():
function getDiscountGrid (line 286) | def getDiscountGrid():
function getBridgeGrid (line 294) | def getBridgeGrid():
function getBookGrid (line 300) | def getBookGrid():
function getMazeGrid (line 306) | def getMazeGrid():
function getUserAction (line 316) | def getUserAction(state, actionFunction):
function printString (line 338) | def printString(x): print x
function runEpisode (line 340) | def runEpisode(agent, environment, discount, decision, display, message,...
function parseOptions (line 380) | def parseOptions():
class RandomAgent (line 500) | class RandomAgent:
method getAction (line 501) | def getAction(self, state):
method getValue (line 503) | def getValue(self, state):
method getQValue (line 505) | def getQValue(self, state, action):
method getPolicy (line 507) | def getPolicy(self, state):
method update (line 510) | def update(self, state, action, nextState, reward):
FILE: Project-3/keyboardAgents.py
class KeyboardAgent (line 19) | class KeyboardAgent(Agent):
method __init__ (line 30) | def __init__( self, index = 0 ):
method getAction (line 36) | def getAction( self, state):
method getMove (line 59) | def getMove(self, legal):
class KeyboardAgent2 (line 67) | class KeyboardAgent2(KeyboardAgent):
method getMove (line 78) | def getMove(self, legal):
FILE: Project-3/layout.py
class Layout (line 22) | class Layout:
method __init__ (line 27) | def __init__(self, layoutText):
method getNumGhosts (line 40) | def getNumGhosts(self):
method initializeVisibilityMatrix (line 43) | def initializeVisibilityMatrix(self):
method isWall (line 64) | def isWall(self, pos):
method getRandomLegalPosition (line 68) | def getRandomLegalPosition(self):
method getRandomCorner (line 76) | def getRandomCorner(self):
method getFurthestCorner (line 80) | def getFurthestCorner(self, pacPos):
method isVisibleFrom (line 85) | def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
method __str__ (line 89) | def __str__(self):
method deepCopy (line 92) | def deepCopy(self):
method processLayoutText (line 95) | def processLayoutText(self, layoutText):
method processLayoutChar (line 116) | def processLayoutChar(self, x, y, layoutChar):
function getLayout (line 131) | def getLayout(name, back = 2):
function tryToLoad (line 145) | def tryToLoad(fullname):
FILE: Project-3/learningAgents.py
class ValueEstimationAgent (line 19) | class ValueEstimationAgent(Agent):
method __init__ (line 36) | def __init__(self, alpha=1.0, epsilon=0.05, gamma=0.8, numTraining = 10):
method getQValue (line 52) | def getQValue(self, state, action):
method getValue (line 58) | def getValue(self, state):
method getPolicy (line 67) | def getPolicy(self, state):
method getAction (line 80) | def getAction(self, state):
class ReinforcementAgent (line 87) | class ReinforcementAgent(ValueEstimationAgent):
method update (line 105) | def update(self, state, action, nextState, reward):
method getLegalActions (line 116) | def getLegalActions(self,state):
method observeTransition (line 124) | def observeTransition(self, state,action,nextState,deltaReward):
method startEpisode (line 135) | def startEpisode(self):
method stopEpisode (line 143) | def stopEpisode(self):
method isInTraining (line 157) | def isInTraining(self):
method isInTesting (line 160) | def isInTesting(self):
method __init__ (line 163) | def __init__(self, actionFn = None, numTraining=100, epsilon=0.5, alph...
method setEpsilon (line 186) | def setEpsilon(self, epsilon):
method setLearningRate (line 189) | def setLearningRate(self, alpha):
method setDiscount (line 192) | def setDiscount(self, discount):
method doAction (line 195) | def doAction(self,state,action):
method observationFunction (line 206) | def observationFunction(self, state):
method registerInitialState (line 216) | def registerInitialState(self, state):
method final (line 221) | def final(self, state):
FILE: Project-3/mdp.py
class MarkovDecisionProcess (line 17) | class MarkovDecisionProcess:
method getStates (line 19) | def getStates(self):
method getStartState (line 26) | def getStartState(self):
method getPossibleActions (line 32) | def getPossibleActions(self, state):
method getTransitionStatesAndProbs (line 38) | def getTransitionStatesAndProbs(self, state, action):
method getReward (line 51) | def getReward(self, state, action, nextState):
method isTerminal (line 59) | def isTerminal(self, state):
FILE: Project-3/pacman.py
class GameState (line 55) | class GameState:
method getAndResetExplored (line 76) | def getAndResetExplored():
method getLegalActions (line 82) | def getLegalActions( self, agentIndex=0 ):
method generateSuccessor (line 94) | def generateSuccessor( self, agentIndex, action):
method getLegalPacmanActions (line 127) | def getLegalPacmanActions( self ):
method generatePacmanSuccessor (line 130) | def generatePacmanSuccessor( self, action ):
method getPacmanState (line 136) | def getPacmanState( self ):
method getPacmanPosition (line 145) | def getPacmanPosition( self ):
method getGhostStates (line 148) | def getGhostStates( self ):
method getGhostState (line 151) | def getGhostState( self, agentIndex ):
method getGhostPosition (line 156) | def getGhostPosition( self, agentIndex ):
method getGhostPositions (line 161) | def getGhostPositions(self):
method getNumAgents (line 164) | def getNumAgents( self ):
method getScore (line 167) | def getScore( self ):
method getCapsules (line 170) | def getCapsules(self):
method getNumFood (line 176) | def getNumFood( self ):
method getFood (line 179) | def getFood(self):
method getWalls (line 191) | def getWalls(self):
method hasFood (line 203) | def hasFood(self, x, y):
method hasWall (line 206) | def hasWall(self, x, y):
method isLose (line 209) | def isLose( self ):
method isWin (line 212) | def isWin( self ):
method __init__ (line 220) | def __init__( self, prevState = None ):
method deepCopy (line 229) | def deepCopy( self ):
method __eq__ (line 234) | def __eq__( self, other ):
method __hash__ (line 240) | def __hash__( self ):
method __str__ (line 246) | def __str__( self ):
method initialize (line 250) | def initialize( self, layout, numGhostAgents=1000 ):
class ClassicGameRules (line 266) | class ClassicGameRules:
method __init__ (line 271) | def __init__(self, timeout=30):
method newGame (line 274) | def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = ...
method process (line 284) | def process(self, state, game):
method win (line 291) | def win( self, state, game ):
method lose (line 295) | def lose( self, state, game ):
method getProgress (line 299) | def getProgress(self, game):
method agentCrash (line 302) | def agentCrash(self, game, agentIndex):
method getMaxTotalTime (line 308) | def getMaxTotalTime(self, agentIndex):
method getMaxStartupTime (line 311) | def getMaxStartupTime(self, agentIndex):
method getMoveWarningTime (line 314) | def getMoveWarningTime(self, agentIndex):
method getMoveTimeout (line 317) | def getMoveTimeout(self, agentIndex):
method getMaxTimeWarnings (line 320) | def getMaxTimeWarnings(self, agentIndex):
class PacmanRules (line 323) | class PacmanRules:
method getLegalActions (line 330) | def getLegalActions( state ):
method applyAction (line 337) | def applyAction( state, action ):
method consume (line 359) | def consume( position, state ):
class GhostRules (line 381) | class GhostRules:
method getLegalActions (line 386) | def getLegalActions( state, ghostIndex ):
method applyAction (line 401) | def applyAction( state, action, ghostIndex):
method decrementTimer (line 414) | def decrementTimer( ghostState):
method checkDeath (line 421) | def checkDeath( state, agentIndex):
method collide (line 436) | def collide( state, ghostState, agentIndex):
method canKill (line 449) | def canKill( pacmanPosition, ghostPosition ):
method placeGhost (line 453) | def placeGhost(state, ghostState):
function default (line 461) | def default(str):
function parseAgentArgs (line 464) | def parseAgentArgs(str):
function readCommand (line 476) | def readCommand( argv ):
function loadAgent (line 587) | def loadAgent(pacman, nographics):
function replayGame (line 610) | def replayGame( layout, actions, display ):
function runGames (line 628) | def runGames( layout, pacman, ghosts, display, numGames, record, numTrai...
FILE: Project-3/pacmanAgents.py
class LeftTurnAgent (line 21) | class LeftTurnAgent(game.Agent):
method getAction (line 24) | def getAction(self, state):
class GreedyAgent (line 35) | class GreedyAgent(Agent):
method __init__ (line 36) | def __init__(self, evalFn="scoreEvaluation"):
method getAction (line 40) | def getAction(self, state):
function scoreEvaluation (line 51) | def scoreEvaluation(state):
FILE: Project-3/qlearningAgents.py
class QLearningAgent (line 21) | class QLearningAgent(ReinforcementAgent):
method __init__ (line 41) | def __init__(self, **args):
method getQValue (line 47) | def getQValue(self, state, action):
method computeValueFromQValues (line 56) | def computeValueFromQValues(self, state):
method computeActionFromQValues (line 69) | def computeActionFromQValues(self, state):
method getAction (line 81) | def getAction(self, state):
method update (line 102) | def update(self, state, action, nextState, reward):
method getPolicy (line 116) | def getPolicy(self, state):
method getValue (line 119) | def getValue(self, state):
class PacmanQAgent (line 123) | class PacmanQAgent(QLearningAgent):
method __init__ (line 126) | def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **...
method getAction (line 144) | def getAction(self, state):
class ApproximateQAgent (line 155) | class ApproximateQAgent(PacmanQAgent):
method __init__ (line 163) | def __init__(self, extractor='IdentityExtractor', **args):
method getWeights (line 168) | def getWeights(self):
method getQValue (line 171) | def getQValue(self, state, action):
method update (line 182) | def update(self, state, action, nextState, reward):
method final (line 192) | def final(self, state):
FILE: Project-3/reinforcementTestClasses.py
class ValueIterationTest (line 31) | class ValueIterationTest(testClasses.TestCase):
method __init__ (line 33) | def __init__(self, question, testDict):
method writeFailureFile (line 46) | def writeFailureFile(self, string):
method removeFailureFileIfExists (line 50) | def removeFailureFileIfExists(self):
method execute (line 54) | def execute(self, grades, moduleDict, solutionDict):
method executeNIterations (line 70) | def executeNIterations(self, grades, moduleDict, solutionDict, n, chec...
method writeSolution (line 109) | def writeSolution(self, moduleDict, filePath):
method runAgent (line 122) | def runAgent(self, moduleDict, numIterations):
method prettyPrint (line 147) | def prettyPrint(self, elements, formatString):
method prettyValues (line 166) | def prettyValues(self, values):
method prettyPolicy (line 169) | def prettyPolicy(self, policy):
method prettyValueSolutionString (line 172) | def prettyValueSolutionString(self, name, pretty):
method comparePrettyValues (line 175) | def comparePrettyValues(self, aPretty, bPretty, tolerance=0.01):
method parsePrettyValues (line 193) | def parsePrettyValues(self, pretty):
class ApproximateQLearningTest (line 198) | class ApproximateQLearningTest(testClasses.TestCase):
method __init__ (line 200) | def __init__(self, question, testDict):
method writeFailureFile (line 221) | def writeFailureFile(self, string):
method removeFailureFileIfExists (line 225) | def removeFailureFileIfExists(self):
method execute (line 229) | def execute(self, grades, moduleDict, solutionDict):
method executeNExperiences (line 244) | def executeNExperiences(self, grades, moduleDict, solutionDict, n):
method writeSolution (line 270) | def writeSolution(self, moduleDict, filePath):
method runAgent (line 279) | def runAgent(self, moduleDict, numExperiences):
method prettyPrint (line 310) | def prettyPrint(self, elements, formatString):
method prettyValues (line 329) | def prettyValues(self, values):
method prettyPolicy (line 332) | def prettyPolicy(self, policy):
method prettyValueSolutionString (line 335) | def prettyValueSolutionString(self, name, pretty):
method comparePrettyValues (line 338) | def comparePrettyValues(self, aPretty, bPretty, tolerance=0.01):
method parsePrettyValues (line 356) | def parsePrettyValues(self, pretty):
class QLearningTest (line 361) | class QLearningTest(testClasses.TestCase):
method __init__ (line 363) | def __init__(self, question, testDict):
method writeFailureFile (line 381) | def writeFailureFile(self, string):
method removeFailureFileIfExists (line 385) | def removeFailureFileIfExists(self):
method execute (line 389) | def execute(self, grades, moduleDict, solutionDict):
method executeNExperiences (line 405) | def executeNExperiences(self, grades, moduleDict, solutionDict, n, che...
method writeSolution (line 442) | def writeSolution(self, moduleDict, filePath):
method runAgent (line 454) | def runAgent(self, moduleDict, numExperiences):
method prettyPrint (line 490) | def prettyPrint(self, elements, formatString):
method prettyValues (line 509) | def prettyValues(self, values):
method prettyPolicy (line 512) | def prettyPolicy(self, policy):
method prettyValueSolutionString (line 515) | def prettyValueSolutionString(self, name, pretty):
method comparePrettyValues (line 518) | def comparePrettyValues(self, aPretty, bPretty, tolerance=0.01):
method parsePrettyValues (line 536) | def parsePrettyValues(self, pretty):
class EpsilonGreedyTest (line 541) | class EpsilonGreedyTest(testClasses.TestCase):
method __init__ (line 543) | def __init__(self, question, testDict):
method execute (line 558) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 564) | def writeSolution(self, moduleDict, filePath):
method runAgent (line 570) | def runAgent(self, moduleDict):
method testEpsilonGreedy (line 584) | def testEpsilonGreedy(self, moduleDict, tolerance=0.025):
class Question6Test (line 610) | class Question6Test(testClasses.TestCase):
method __init__ (line 612) | def __init__(self, question, testDict):
method execute (line 615) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 626) | def writeSolution(self, moduleDict, filePath):
class EvalAgentTest (line 638) | class EvalAgentTest(testClasses.TestCase):
method __init__ (line 640) | def __init__(self, question, testDict):
method execute (line 655) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 715) | def writeSolution(self, moduleDict, filePath):
function followPath (line 728) | def followPath(policy, start, numSteps=100):
function parseGrid (line 747) | def parseGrid(string):
function computePolicy (line 761) | def computePolicy(moduleDict, grid, discount):
class GridPolicyTest (line 770) | class GridPolicyTest(testClasses.TestCase):
method __init__ (line 772) | def __init__(self, question, testDict):
method execute (line 806) | def execute(self, grades, moduleDict, solutionDict):
method printGridworld (line 896) | def printGridworld(self):
method printPolicy (line 902) | def printPolicy(self, policy, policyTypeIsGrid):
method writeSolution (line 919) | def writeSolution(self, moduleDict, filePath):
FILE: Project-3/testClasses.py
class Question (line 24) | class Question(object):
method raiseNotDefined (line 26) | def raiseNotDefined(self):
method __init__ (line 30) | def __init__(self, questionDict, display):
method getDisplay (line 35) | def getDisplay(self):
method getMaxPoints (line 38) | def getMaxPoints(self):
method addTestCase (line 43) | def addTestCase(self, testCase, thunk):
method execute (line 46) | def execute(self, grades):
class PassAllTestsQuestion (line 50) | class PassAllTestsQuestion(Question):
method execute (line 52) | def execute(self, grades):
class HackedPartialCreditQuestion (line 67) | class HackedPartialCreditQuestion(Question):
method execute (line 69) | def execute(self, grades):
class Q6PartialCreditQuestion (line 89) | class Q6PartialCreditQuestion(Question):
method execute (line 93) | def execute(self, grades):
class PartialCreditQuestion (line 102) | class PartialCreditQuestion(Question):
method execute (line 106) | def execute(self, grades):
class NumberPassedQuestion (line 117) | class NumberPassedQuestion(Question):
method execute (line 120) | def execute(self, grades):
class TestCase (line 128) | class TestCase(object):
method raiseNotDefined (line 130) | def raiseNotDefined(self):
method getPath (line 134) | def getPath(self):
method __init__ (line 137) | def __init__(self, question, testDict):
method __str__ (line 143) | def __str__(self):
method execute (line 146) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 149) | def writeSolution(self, moduleDict, filePath):
method testPass (line 159) | def testPass(self, grades):
method testFail (line 165) | def testFail(self, grades):
method testPartial (line 173) | def testPartial(self, grades, points, maxPoints):
method addMessage (line 187) | def addMessage(self, message):
FILE: Project-3/testParser.py
class TestParser (line 18) | class TestParser(object):
method __init__ (line 20) | def __init__(self, path):
method removeComments (line 24) | def removeComments(self, rawlines):
method parse (line 35) | def parse(self):
function emitTestDict (line 76) | def emitTestDict(testDict, handle):
FILE: Project-3/textDisplay.py
class NullGraphics (line 26) | class NullGraphics:
method initialize (line 27) | def initialize(self, state, isBlue = False):
method update (line 30) | def update(self, state):
method checkNullDisplay (line 33) | def checkNullDisplay(self):
method pause (line 36) | def pause(self):
method draw (line 39) | def draw(self, state):
method updateDistributions (line 42) | def updateDistributions(self, dist):
method finish (line 45) | def finish(self):
class PacmanGraphics (line 48) | class PacmanGraphics:
method __init__ (line 49) | def __init__(self, speed=None):
method initialize (line 54) | def initialize(self, state, isBlue = False):
method update (line 60) | def update(self, state):
method pause (line 74) | def pause(self):
method draw (line 77) | def draw(self, state):
method finish (line 80) | def finish(self):
FILE: Project-3/textGridworldDisplay.py
class TextGridworldDisplay (line 17) | class TextGridworldDisplay:
method __init__ (line 19) | def __init__(self, gridworld):
method start (line 22) | def start(self):
method pause (line 25) | def pause(self):
method displayValues (line 28) | def displayValues(self, agent, currentState = None, message = None):
method displayNullValues (line 39) | def displayNullValues(self, agent, currentState = None, message = None):
method displayQValues (line 43) | def displayQValues(self, agent, currentState = None, message = None):
function prettyPrintValues (line 53) | def prettyPrintValues(gridWorld, values, policy=None, currentState = None):
function prettyPrintNullValues (line 109) | def prettyPrintNullValues(gridWorld, currentState = None):
function prettyPrintQValues (line 176) | def prettyPrintQValues(gridWorld, qValues, currentState=None):
function border (line 247) | def border(text):
function indent (line 259) | def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='...
function wrap_always (line 301) | def wrap_always(text, width):
FILE: Project-3/util.py
class FixedRandom (line 21) | class FixedRandom:
method __init__ (line 22) | def __init__(self):
class Stack (line 120) | class Stack:
method __init__ (line 122) | def __init__(self):
method push (line 125) | def push(self,item):
method pop (line 129) | def pop(self):
method isEmpty (line 133) | def isEmpty(self):
class Queue (line 137) | class Queue:
method __init__ (line 139) | def __init__(self):
method push (line 142) | def push(self,item):
method pop (line 146) | def pop(self):
method isEmpty (line 153) | def isEmpty(self):
class PriorityQueue (line 157) | class PriorityQueue:
method __init__ (line 168) | def __init__(self):
method push (line 172) | def push(self, item, priority):
method pop (line 180) | def pop(self):
method isEmpty (line 185) | def isEmpty(self):
class PriorityQueueWithFunction (line 188) | class PriorityQueueWithFunction(PriorityQueue):
method __init__ (line 195) | def __init__(self, priorityFunction):
method push (line 200) | def push(self, item):
function manhattanDistance (line 205) | def manhattanDistance( xy1, xy2 ):
class Counter (line 215) | class Counter(dict):
method __getitem__ (line 255) | def __getitem__(self, idx):
method incrementAll (line 259) | def incrementAll(self, keys, count):
method argMax (line 273) | def argMax(self):
method sortedKeys (line 283) | def sortedKeys(self):
method totalCount (line 300) | def totalCount(self):
method normalize (line 306) | def normalize(self):
method divideAll (line 318) | def divideAll(self, divisor):
method copy (line 326) | def copy(self):
method __mul__ (line 332) | def __mul__(self, y ):
method __radd__ (line 358) | def __radd__(self, y):
method __add__ (line 376) | def __add__( self, y ):
method __sub__ (line 402) | def __sub__( self, y ):
function raiseNotDefined (line 428) | def raiseNotDefined():
function normalize (line 436) | def normalize(vectorOrCounter):
function nSample (line 455) | def nSample(distribution, values, n):
function sample (line 471) | def sample(distribution, values = None):
function sampleFromCounter (line 485) | def sampleFromCounter(ctr):
function getProbability (line 489) | def getProbability(value, distribution, values):
function flipCoin (line 500) | def flipCoin( p ):
function chooseFromDistribution (line 504) | def chooseFromDistribution( distribution ):
function nearestPoint (line 514) | def nearestPoint( pos ):
function sign (line 524) | def sign( x ):
function arrayInvert (line 533) | def arrayInvert(array):
function matrixAsList (line 543) | def matrixAsList( matrix, value = True ):
function lookup (line 555) | def lookup(name, namespace):
function pause (line 573) | def pause():
class TimeoutFunctionException (line 591) | class TimeoutFunctionException(Exception):
class TimeoutFunction (line 596) | class TimeoutFunction:
method __init__ (line 597) | def __init__(self, function, timeout):
method handle_timeout (line 601) | def handle_timeout(self, signum, frame):
method __call__ (line 604) | def __call__(self, *args, **keyArgs):
class WritableNull (line 630) | class WritableNull:
method write (line 631) | def write(self, string):
function mutePrint (line 634) | def mutePrint():
function unmutePrint (line 645) | def unmutePrint():
FILE: Project-3/valueIterationAgents.py
class ValueIterationAgent (line 19) | class ValueIterationAgent(ValueEstimationAgent):
method __init__ (line 28) | def __init__(self, mdp, discount = 0.9, iterations = 100):
method getValue (line 57) | def getValue(self, state):
method computeQValueFromValues (line 64) | def computeQValueFromValues(self, state, action):
method computeActionFromValues (line 74) | def computeActionFromValues(self, state):
method getPolicy (line 93) | def getPolicy(self, state):
method getAction (line 96) | def getAction(self, state):
method getQValue (line 100) | def getQValue(self, state, action):
FILE: Project-4/autograder.py
function readCommand (line 31) | def readCommand(argv):
function confirmGenerate (line 83) | def confirmGenerate():
function setModuleName (line 100) | def setModuleName(module, filename):
function loadModuleString (line 118) | def loadModuleString(moduleSource):
function loadModuleFile (line 131) | def loadModuleFile(moduleName, filePath):
function readFile (line 136) | def readFile(path, root=""):
function splitStrings (line 173) | def splitStrings(d):
function printTest (line 184) | def printTest(testDict, solutionDict):
function runTest (line 194) | def runTest(testName, moduleDict, printTestCase=False, display=None):
function getDepends (line 219) | def getDepends(testParser, testRoot, question):
function getTestSubdirs (line 230) | def getTestSubdirs(testParser, testRoot, questionToGrade):
function evaluate (line 243) | def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR...
function getDisplay (line 310) | def getDisplay(graphicsByDefault, options=None):
FILE: Project-4/busters.py
function getNoisyDistance (line 42) | def getNoisyDistance(pos1, pos2):
function getObservationDistribution (line 48) | def getObservationDistribution(noisyDistance):
class GameState (line 67) | class GameState:
method getLegalActions (line 86) | def getLegalActions( self, agentIndex=0 ):
method generateSuccessor (line 97) | def generateSuccessor( self, agentIndex, action):
method getLegalPacmanActions (line 132) | def getLegalPacmanActions( self ):
method generatePacmanSuccessor (line 135) | def generatePacmanSuccessor( self, action ):
method getPacmanState (line 141) | def getPacmanState( self ):
method getPacmanPosition (line 150) | def getPacmanPosition( self ):
method getNumAgents (line 153) | def getNumAgents( self ):
method getScore (line 156) | def getScore( self ):
method getCapsules (line 159) | def getCapsules(self):
method getNumFood (line 165) | def getNumFood( self ):
method getFood (line 168) | def getFood(self):
method getWalls (line 180) | def getWalls(self):
method hasFood (line 192) | def hasFood(self, x, y):
method hasWall (line 195) | def hasWall(self, x, y):
method getLivingGhosts (line 202) | def getLivingGhosts(self):
method setGhostNotLiving (line 210) | def setGhostNotLiving(self, index):
method isLose (line 213) | def isLose( self ):
method isWin (line 216) | def isWin( self ):
method getNoisyGhostDistances (line 219) | def getNoisyGhostDistances(self):
method __init__ (line 230) | def __init__( self, prevState = None ):
method deepCopy (line 245) | def deepCopy( self ):
method __eq__ (line 251) | def __eq__( self, other ):
method __hash__ (line 257) | def __hash__( self ):
method __str__ (line 263) | def __str__( self ):
method initialize (line 267) | def initialize( self, layout, numGhostAgents=1000 ):
method getGhostPosition (line 275) | def getGhostPosition( self, agentIndex ):
method getGhostState (line 280) | def getGhostState( self, agentIndex ):
class BustersGameRules (line 294) | class BustersGameRules:
method newGame (line 300) | def newGame( self, layout, pacmanAgent, ghostAgents, display, maxMoves...
method process (line 309) | def process(self, state, game):
method win (line 316) | def win( self, state, game ):
method lose (line 319) | def lose( self, state, game ):
class PacmanRules (line 322) | class PacmanRules:
method getLegalActions (line 327) | def getLegalActions( state ):
method applyAction (line 334) | def applyAction( state, action ):
class GhostRules (line 350) | class GhostRules:
method getLegalActions (line 354) | def getLegalActions( state, ghostIndex ):
method applyAction (line 359) | def applyAction( state, action, ghostIndex):
method decrementTimer (line 369) | def decrementTimer( ghostState):
method checkDeath (line 376) | def checkDeath( state, agentIndex):
method collide (line 391) | def collide( state, ghostState, agentIndex):
method canKill (line 399) | def canKill( pacmanPosition, ghostPosition ):
method placeGhost (line 403) | def placeGhost(ghostState, agentIndex):
class RandomGhost (line 409) | class RandomGhost:
method __init__ (line 410) | def __init__( self, index ):
method getAction (line 413) | def getAction( self, state ):
method getDistribution (line 416) | def getDistribution( self, state ):
function default (line 425) | def default(str):
function parseAgentArgs (line 428) | def parseAgentArgs(str):
function readCommand (line 440) | def readCommand( argv ):
function loadAgent (line 510) | def loadAgent(pacman, nographics):
function runGames (line 533) | def runGames( layout, pacman, ghosts, display, numGames, maxMoves=-1):
FILE: Project-4/bustersAgents.py
class NullGraphics (line 22) | class NullGraphics:
method initialize (line 24) | def initialize(self, state, isBlue = False):
method update (line 26) | def update(self, state):
method pause (line 28) | def pause(self):
method draw (line 30) | def draw(self, state):
method updateDistributions (line 32) | def updateDistributions(self, dist):
method finish (line 34) | def finish(self):
class KeyboardInference (line 37) | class KeyboardInference(inference.InferenceModule):
method initializeUniformly (line 41) | def initializeUniformly(self, gameState):
method observe (line 47) | def observe(self, observation, gameState):
method elapseTime (line 59) | def elapseTime(self, gameState):
method getBeliefDistribution (line 62) | def getBeliefDistribution(self):
class BustersAgent (line 66) | class BustersAgent:
method __init__ (line 69) | def __init__( self, index = 0, inference = "ExactInference", ghostAgen...
method registerInitialState (line 75) | def registerInitialState(self, gameState):
method observationFunction (line 84) | def observationFunction(self, gameState):
method getAction (line 90) | def getAction(self, gameState):
method chooseAction (line 102) | def chooseAction(self, gameState):
class BustersKeyboardAgent (line 106) | class BustersKeyboardAgent(BustersAgent, KeyboardAgent):
method __init__ (line 109) | def __init__(self, index = 0, inference = "KeyboardInference", ghostAg...
method getAction (line 113) | def getAction(self, gameState):
method chooseAction (line 116) | def chooseAction(self, gameState):
class GreedyBustersAgent (line 123) | class GreedyBustersAgent(BustersAgent):
method registerInitialState (line 126) | def registerInitialState(self, gameState):
method chooseAction (line 131) | def chooseAction(self, gameState):
FILE: Project-4/bustersGhostAgents.py
class StationaryGhost (line 21) | class StationaryGhost( ghostAgents.GhostAgent ):
method getDistribution (line 22) | def getDistribution( self, state ):
class DispersingGhost (line 27) | class DispersingGhost( ghostAgents.GhostAgent ):
method __init__ (line 29) | def __init__( self, index, spreadProb=0.5):
method getDistribution (line 33) | def getDistribution( self, state ):
FILE: Project-4/distanceCalculator.py
class Distancer (line 35) | class Distancer:
method __init__ (line 36) | def __init__(self, layout, background=True, default=10000):
method getDistance (line 58) | def getDistance(self, pos1, pos2):
method getDistanceOnGrid (line 77) | def getDistanceOnGrid(self, pos1, pos2):
method isReadyForMazeDistance (line 84) | def isReadyForMazeDistance(self):
function manhattanDistance (line 87) | def manhattanDistance(x, y ):
function isInt (line 90) | def isInt(pos):
function getGrids2D (line 94) | def getGrids2D(pos):
function getGrids1D (line 101) | def getGrids1D(x):
function waitOnDistanceCalculator (line 115) | def waitOnDistanceCalculator(t):
class DistanceCalculator (line 120) | class DistanceCalculator(threading.Thread):
method setAttr (line 121) | def setAttr(self, layout, distancer, default = 10000):
method run (line 126) | def run(self):
function computeDistances (line 145) | def computeDistances(layout):
function getDistanceOnGrid (line 186) | def getDistanceOnGrid(distances, pos1, pos2):
FILE: Project-4/game.py
class Agent (line 32) | class Agent:
method __init__ (line 39) | def __init__(self, index=0):
method getAction (line 42) | def getAction(self, state):
class Directions (line 49) | class Directions:
class Configuration (line 70) | class Configuration:
method __init__ (line 79) | def __init__(self, pos, direction):
method getPosition (line 83) | def getPosition(self):
method getDirection (line 86) | def getDirection(self):
method isInteger (line 89) | def isInteger(self):
method __eq__ (line 93) | def __eq__(self, other):
method __hash__ (line 97) | def __hash__(self):
method __str__ (line 102) | def __str__(self):
method generateSuccessor (line 105) | def generateSuccessor(self, vector):
class AgentState (line 120) | class AgentState:
method __init__ (line 125) | def __init__( self, startConfiguration, isPacman ):
method __str__ (line 133) | def __str__( self ):
method __eq__ (line 139) | def __eq__( self, other ):
method __hash__ (line 144) | def __hash__(self):
method copy (line 147) | def copy( self ):
method getPosition (line 155) | def getPosition(self):
method getDirection (line 159) | def getDirection(self):
class Grid (line 162) | class Grid:
method __init__ (line 170) | def __init__(self, width, height, initialValue=False, bitRepresentatio...
method __getitem__ (line 180) | def __getitem__(self, i):
method __setitem__ (line 183) | def __setitem__(self, key, item):
method __str__ (line 186) | def __str__(self):
method __eq__ (line 191) | def __eq__(self, other):
method __hash__ (line 195) | def __hash__(self):
method copy (line 206) | def copy(self):
method deepCopy (line 211) | def deepCopy(self):
method shallowCopy (line 214) | def shallowCopy(self):
method count (line 219) | def count(self, item =True ):
method asList (line 222) | def asList(self, key = True):
method packBits (line 229) | def packBits(self):
method _cellIndexToPosition (line 248) | def _cellIndexToPosition(self, index):
method _unpackBits (line 253) | def _unpackBits(self, bits):
method _unpackInt (line 265) | def _unpackInt(self, packed, size):
function reconstituteGrid (line 277) | def reconstituteGrid(bitRep):
class Actions (line 287) | class Actions:
method reverseDirection (line 302) | def reverseDirection(action):
method vectorToDirection (line 314) | def vectorToDirection(vector):
method directionToVector (line 327) | def directionToVector(direction, speed = 1.0):
method getPossibleActions (line 332) | def getPossibleActions(config, walls):
method getLegalNeighbors (line 351) | def getLegalNeighbors(position, walls):
method getSuccessor (line 365) | def getSuccessor(position, action):
class GameStateData (line 371) | class GameStateData:
method __init__ (line 375) | def __init__( self, prevState = None ):
method deepCopy (line 395) | def deepCopy( self ):
method copyAgentStates (line 405) | def copyAgentStates( self, agentStates ):
method __eq__ (line 411) | def __eq__( self, other ):
method __hash__ (line 423) | def __hash__( self ):
method __str__ (line 435) | def __str__( self ):
method _foodWallStr (line 460) | def _foodWallStr( self, hasFood, hasWall ):
method _pacStr (line 468) | def _pacStr( self, dir ):
method _ghostStr (line 477) | def _ghostStr( self, dir ):
method initialize (line 487) | def initialize( self, layout, numGhostAgents ):
class Game (line 513) | class Game:
method __init__ (line 518) | def __init__( self, agents, display, rules, startingIndex=0, muteAgent...
method getProgress (line 534) | def getProgress(self):
method _agentCrash (line 540) | def _agentCrash( self, agentIndex, quiet=False):
method mute (line 550) | def mute(self, agentIndex):
method unmute (line 559) | def unmute(self):
method run (line 567) | def run( self ):
FILE: Project-4/ghostAgents.py
class GhostAgent (line 22) | class GhostAgent( Agent ):
method __init__ (line 23) | def __init__( self, index ):
method getAction (line 26) | def getAction( self, state ):
method getDistribution (line 33) | def getDistribution(self, state):
class RandomGhost (line 37) | class RandomGhost( GhostAgent ):
method getDistribution (line 39) | def getDistribution( self, state ):
class DirectionalGhost (line 45) | class DirectionalGhost( GhostAgent ):
method __init__ (line 47) | def __init__( self, index, prob_attack=0.8, prob_scaredFlee=0.8 ):
method getDistribution (line 52) | def getDistribution( self, state ):
FILE: Project-4/grading.py
class Grades (line 25) | class Grades:
method __init__ (line 27) | def __init__(self, projectName, questionsAndMaxesList, edxOutput=False...
method addPrereq (line 48) | def addPrereq(self, question, prereq):
method grade (line 51) | def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
method addExceptionMessage (line 139) | def addExceptionMessage(self, q, inst, traceback):
method addErrorHints (line 149) | def addErrorHints(self, exceptionMap, errorInstance, questionNum):
method produceOutput (line 171) | def produceOutput(self):
method fail (line 227) | def fail(self, message, raw=False):
method assignZeroCredit (line 233) | def assignZeroCredit(self):
method addPoints (line 236) | def addPoints(self, amt):
method deductPoints (line 239) | def deductPoints(self, amt):
method assignFullCredit (line 242) | def assignFullCredit(self, message="", raw=False):
method addMessage (line 247) | def addMessage(self, message, raw=False):
method addMessageToEmail (line 256) | def addMessageToEmail(self, message):
class Counter (line 267) | class Counter(dict):
method __getitem__ (line 271) | def __getitem__(self, idx):
method totalCount (line 277) | def totalCount(self):
FILE: Project-4/graphicsDisplay.py
class InfoPane (line 82) | class InfoPane:
method __init__ (line 83) | def __init__(self, layout, gridSize):
method toScreen (line 92) | def toScreen(self, pos, y = None):
method drawPane (line 105) | def drawPane(self):
method initializeGhostDistances (line 108) | def initializeGhostDistances(self, distances):
method updateScore (line 121) | def updateScore(self, score):
method setTeam (line 124) | def setTeam(self, isBlue):
method updateGhostDistances (line 129) | def updateGhostDistances(self, distances):
method drawGhost (line 136) | def drawGhost(self):
method drawPacman (line 139) | def drawPacman(self):
method drawWarning (line 142) | def drawWarning(self):
method clearIcon (line 145) | def clearIcon(self):
method updateMessage (line 148) | def updateMessage(self, message):
method clearMessage (line 151) | def clearMessage(self):
class PacmanGraphics (line 155) | class PacmanGraphics:
method __init__ (line 156) | def __init__(self, zoom=1.0, frameTime=0.0, capture=False):
method checkNullDisplay (line 165) | def checkNullDisplay(self):
method initialize (line 168) | def initialize(self, state, isBlue = False):
method startGraphics (line 180) | def startGraphics(self, state):
method drawDistributions (line 189) | def drawDistributions(self, state):
method drawStaticObjects (line 204) | def drawStaticObjects(self, state):
method drawAgentObjects (line 211) | def drawAgentObjects(self, state):
method swapImages (line 222) | def swapImages(self, agentIndex, newState):
method update (line 236) | def update(self, newState):
method make_window (line 256) | def make_window(self, width, height):
method drawPacman (line 267) | def drawPacman(self, pacman, index):
method getEndpoints (line 286) | def getEndpoints(self, direction, position=(0,0)):
method movePacman (line 302) | def movePacman(self, position, direction, image):
method animatePacman (line 309) | def animatePacman(self, pacman, prevPacman, image):
method getGhostColor (line 329) | def getGhostColor(self, ghost, ghostIndex):
method drawGhost (line 335) | def drawGhost(self, ghost, agentIndex):
method moveEyes (line 371) | def moveEyes(self, pos, dir, eyes):
method moveGhost (line 388) | def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
method getPosition (line 405) | def getPosition(self, agentState):
method getDirection (line 409) | def getDirection(self, agentState):
method finish (line 413) | def finish(self):
method to_screen (line 416) | def to_screen(self, point):
method to_screen2 (line 424) | def to_screen2(self, point):
method drawWalls (line 431) | def drawWalls(self, wallMatrix):
method isWall (line 517) | def isWall(self, x, y, walls):
method drawFood (line 524) | def drawFood(self, foodMatrix ):
method drawCapsules (line 544) | def drawCapsules(self, capsules ):
method removeFood (line 556) | def removeFood(self, cell, foodImages ):
method removeCapsule (line 560) | def removeCapsule(self, cell, capsuleImages ):
method drawExpandedCells (line 564) | def drawExpandedCells(self, cells):
method clearExpandedCells (line 583) | def clearExpandedCells(self):
method updateDistributions (line 589) | def updateDistributions(self, distributions):
class FirstPersonPacmanGraphics (line 611) | class FirstPersonPacmanGraphics(PacmanGraphics):
method __init__ (line 612) | def __init__(self, zoom = 1.0, showGhosts = True, capture = False, fra...
method initialize (line 617) | def initialize(self, state, isBlue = False):
method lookAhead (line 634) | def lookAhead(self, config, state):
method getGhostColor (line 648) | def getGhostColor(self, ghost, ghostIndex):
method getPosition (line 651) | def getPosition(self, ghostState):
function add (line 657) | def add(x, y):
function saveFrame (line 672) | def saveFrame():
FILE: Project-4/graphicsUtils.py
function formatColor (line 35) | def formatColor(r, g, b):
function colorToVector (line 38) | def colorToVector(color):
function sleep (line 47) | def sleep(secs):
function begin_graphics (line 56) | def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), ti...
function _leftclick (line 101) | def _leftclick(event):
function _rightclick (line 105) | def _rightclick(event):
function _ctrl_leftclick (line 109) | def _ctrl_leftclick(event):
function wait_for_click (line 113) | def wait_for_click():
function draw_background (line 132) | def draw_background():
function _destroy_window (line 136) | def _destroy_window(event=None):
function end_graphics (line 143) | def end_graphics():
function clear_screen (line 158) | def clear_screen(background=None):
function polygon (line 164) | def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, ...
function square (line 176) | def square(pos, r, color, filled=1, behind=0):
function circle (line 181) | def circle(pos, r, outlineColor, fillColor, endpoints=None, style='piesl...
function image (line 194) | def image(pos, file="../../blueghost.gif"):
function refresh (line 200) | def refresh():
function moveCircle (line 203) | def moveCircle(id, pos, r, endpoints=None):
function edit (line 220) | def edit(id, *args):
function text (line 223) | def text(pos, color, contents, font='Helvetica', size=12, style='normal'...
function changeText (line 229) | def changeText(id, newText, font=None, size=12, style='normal'):
function changeColor (line 234) | def changeColor(id, newColor):
function line (line 237) | def line(here, there, color=formatColor(0, 0, 0), width=2):
function _keypress (line 254) | def _keypress(event):
function _keyrelease (line 262) | def _keyrelease(event):
function remap_arrows (line 271) | def remap_arrows(event):
function _clear_keys (line 284) | def _clear_keys(event=None):
function keys_pressed (line 290) | def keys_pressed(d_o_e=Tkinter.tkinter.dooneevent,
function keys_waiting (line 297) | def keys_waiting():
function wait_for_keys (line 305) | def wait_for_keys():
function remove_from_screen (line 312) | def remove_from_screen(x,
function _adjust_coords (line 318) | def _adjust_coords(coord_list, x, y):
function move_to (line 324) | def move_to(object, x, y=None,
function move_by (line 346) | def move_by(object, x, y=None,
function writePostscript (line 369) | def writePostscript(filename):
FILE: Project-4/inference.py
class InferenceModule (line 21) | class InferenceModule:
method __init__ (line 31) | def __init__(self, ghostAgent):
method getJailPosition (line 37) | def getJailPosition(self):
method getPositionDistribution (line 40) | def getPositionDistribution(self, gameState):
method setGhostPosition (line 56) | def setGhostPosition(self, gameState, ghostPosition):
method observeState (line 74) | def observeState(self, gameState):
method initialize (line 82) | def initialize(self, gameState):
method initializeUniformly (line 92) | def initializeUniformly(self, gameState):
method observe (line 96) | def observe(self, observation, gameState):
method elapseTime (line 100) | def elapseTime(self, gameState):
method getBeliefDistribution (line 104) | def getBeliefDistribution(self):
class ExactInference (line 111) | class ExactInference(InferenceModule):
method initializeUniformly (line 117) | def initializeUniformly(self, gameState):
method observe (line 124) | def observe(self, observation, gameState):
method elapseTime (line 168) | def elapseTime(self, gameState):
method getBeliefDistribution (line 230) | def getBeliefDistribution(self):
class ParticleFilter (line 233) | class ParticleFilter(InferenceModule):
method __init__ (line 242) | def __init__(self, ghostAgent, numParticles=300):
method setNumParticles (line 246) | def setNumParticles(self, numParticles):
method initializeUniformly (line 250) | def initializeUniformly(self, gameState):
method observe (line 271) | def observe(self, observation, gameState):
method elapseTime (line 319) | def elapseTime(self, gameState):
method getBeliefDistribution (line 339) | def getBeliefDistribution(self):
class MarginalInference (line 352) | class MarginalInference(InferenceModule):
method initializeUniformly (line 358) | def initializeUniformly(self, gameState):
method observeState (line 364) | def observeState(self, gameState):
method elapseTime (line 369) | def elapseTime(self, gameState):
method getBeliefDistribution (line 374) | def getBeliefDistribution(self):
class JointParticleFilter (line 382) | class JointParticleFilter:
method __init__ (line 388) | def __init__(self, numParticles=600):
method setNumParticles (line 391) | def setNumParticles(self, numParticles):
method initialize (line 394) | def initialize(self, gameState, legalPositions):
method initializeParticles (line 401) | def initializeParticles(self):
method addGhostAgent (line 433) | def addGhostAgent(self, agent):
method getJailPosition (line 440) | def getJailPosition(self, i):
method observeState (line 443) | def observeState(self, gameState):
method getParticleWithGhostInJail (line 499) | def getParticleWithGhostInJail(self, particle, ghostIndex):
method elapseTime (line 508) | def elapseTime(self, gameState):
method getBeliefDistribution (line 561) | def getBeliefDistribution(self):
function getPositionDistributionForGhost (line 571) | def getPositionDistributionForGhost(gameState, ghostIndex, agent):
function setGhostPositions (line 585) | def setGhostPositions(gameState, ghostPositions):
FILE: Project-4/keyboardAgents.py
class KeyboardAgent (line 19) | class KeyboardAgent(Agent):
method __init__ (line 30) | def __init__( self, index = 0 ):
method getAction (line 36) | def getAction( self, state):
method getMove (line 59) | def getMove(self, legal):
class KeyboardAgent2 (line 67) | class KeyboardAgent2(KeyboardAgent):
method getMove (line 78) | def getMove(self, legal):
FILE: Project-4/layout.py
class Layout (line 22) | class Layout:
method __init__ (line 27) | def __init__(self, layoutText):
method getNumGhosts (line 40) | def getNumGhosts(self):
method initializeVisibilityMatrix (line 43) | def initializeVisibilityMatrix(self):
method isWall (line 64) | def isWall(self, pos):
method getRandomLegalPosition (line 68) | def getRandomLegalPosition(self):
method getRandomCorner (line 76) | def getRandomCorner(self):
method getFurthestCorner (line 80) | def getFurthestCorner(self, pacPos):
method isVisibleFrom (line 85) | def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
method __str__ (line 89) | def __str__(self):
method deepCopy (line 92) | def deepCopy(self):
method processLayoutText (line 95) | def processLayoutText(self, layoutText):
method processLayoutChar (line 116) | def processLayoutChar(self, x, y, layoutChar):
function getLayout (line 131) | def getLayout(name, back = 2):
function tryToLoad (line 145) | def tryToLoad(fullname):
FILE: Project-4/pacman.py
class GameState (line 55) | class GameState:
method getAndResetExplored (line 76) | def getAndResetExplored():
method getLegalActions (line 82) | def getLegalActions( self, agentIndex=0 ):
method generateSuccessor (line 94) | def generateSuccessor( self, agentIndex, action):
method getLegalPacmanActions (line 127) | def getLegalPacmanActions( self ):
method generatePacmanSuccessor (line 130) | def generatePacmanSuccessor( self, action ):
method getPacmanState (line 136) | def getPacmanState( self ):
method getPacmanPosition (line 145) | def getPacmanPosition( self ):
method getGhostStates (line 148) | def getGhostStates( self ):
method getGhostState (line 151) | def getGhostState( self, agentIndex ):
method getGhostPosition (line 156) | def getGhostPosition( self, agentIndex ):
method getGhostPositions (line 161) | def getGhostPositions(self):
method getNumAgents (line 164) | def getNumAgents( self ):
method getScore (line 167) | def getScore( self ):
method getCapsules (line 170) | def getCapsules(self):
method getNumFood (line 176) | def getNumFood( self ):
method getFood (line 179) | def getFood(self):
method getWalls (line 191) | def getWalls(self):
method hasFood (line 203) | def hasFood(self, x, y):
method hasWall (line 206) | def hasWall(self, x, y):
method isLose (line 209) | def isLose( self ):
method isWin (line 212) | def isWin( self ):
method __init__ (line 220) | def __init__( self, prevState = None ):
method deepCopy (line 229) | def deepCopy( self ):
method __eq__ (line 234) | def __eq__( self, other ):
method __hash__ (line 240) | def __hash__( self ):
method __str__ (line 246) | def __str__( self ):
method initialize (line 250) | def initialize( self, layout, numGhostAgents=1000 ):
class ClassicGameRules (line 266) | class ClassicGameRules:
method __init__ (line 271) | def __init__(self, timeout=30):
method newGame (line 274) | def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = ...
method process (line 284) | def process(self, state, game):
method win (line 291) | def win( self, state, game ):
method lose (line 295) | def lose( self, state, game ):
method getProgress (line 299) | def getProgress(self, game):
method agentCrash (line 302) | def agentCrash(self, game, agentIndex):
method getMaxTotalTime (line 308) | def getMaxTotalTime(self, agentIndex):
method getMaxStartupTime (line 311) | def getMaxStartupTime(self, agentIndex):
method getMoveWarningTime (line 314) | def getMoveWarningTime(self, agentIndex):
method getMoveTimeout (line 317) | def getMoveTimeout(self, agentIndex):
method getMaxTimeWarnings (line 320) | def getMaxTimeWarnings(self, agentIndex):
class PacmanRules (line 323) | class PacmanRules:
method getLegalActions (line 330) | def getLegalActions( state ):
method applyAction (line 337) | def applyAction( state, action ):
method consume (line 359) | def consume( position, state ):
class GhostRules (line 381) | class GhostRules:
method getLegalActions (line 386) | def getLegalActions( state, ghostIndex ):
method applyAction (line 401) | def applyAction( state, action, ghostIndex):
method decrementTimer (line 414) | def decrementTimer( ghostState):
method checkDeath (line 421) | def checkDeath( state, agentIndex):
method collide (line 436) | def collide( state, ghostState, agentIndex):
method canKill (line 449) | def canKill( pacmanPosition, ghostPosition ):
method placeGhost (line 453) | def placeGhost(state, ghostState):
function default (line 461) | def default(str):
function parseAgentArgs (line 464) | def parseAgentArgs(str):
function readCommand (line 476) | def readCommand( argv ):
function loadAgent (line 587) | def loadAgent(pacman, nographics):
function replayGame (line 610) | def replayGame( layout, actions, display ):
function runGames (line 628) | def runGames( layout, pacman, ghosts, display, numGames, record, numTrai...
FILE: Project-4/testClasses.py
class Question (line 24) | class Question(object):
method raiseNotDefined (line 26) | def raiseNotDefined(self):
method __init__ (line 30) | def __init__(self, questionDict, display):
method getDisplay (line 35) | def getDisplay(self):
method getMaxPoints (line 38) | def getMaxPoints(self):
method addTestCase (line 43) | def addTestCase(self, testCase, thunk):
method execute (line 46) | def execute(self, grades):
class PassAllTestsQuestion (line 50) | class PassAllTestsQuestion(Question):
method execute (line 52) | def execute(self, grades):
class HackedPartialCreditQuestion (line 67) | class HackedPartialCreditQuestion(Question):
method execute (line 69) | def execute(self, grades):
class Q6PartialCreditQuestion (line 89) | class Q6PartialCreditQuestion(Question):
method execute (line 93) | def execute(self, grades):
class PartialCreditQuestion (line 102) | class PartialCreditQuestion(Question):
method execute (line 106) | def execute(self, grades):
class NumberPassedQuestion (line 117) | class NumberPassedQuestion(Question):
method execute (line 120) | def execute(self, grades):
class TestCase (line 128) | class TestCase(object):
method raiseNotDefined (line 130) | def raiseNotDefined(self):
method getPath (line 134) | def getPath(self):
method __init__ (line 137) | def __init__(self, question, testDict):
method __str__ (line 143) | def __str__(self):
method execute (line 146) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 149) | def writeSolution(self, moduleDict, filePath):
method testPass (line 159) | def testPass(self, grades):
method testFail (line 165) | def testFail(self, grades):
method testPartial (line 173) | def testPartial(self, grades, points, maxPoints):
method addMessage (line 187) | def addMessage(self, message):
FILE: Project-4/testParser.py
class TestParser (line 18) | class TestParser(object):
method __init__ (line 20) | def __init__(self, path):
method removeComments (line 24) | def removeComments(self, rawlines):
method parse (line 35) | def parse(self):
function emitTestDict (line 76) | def emitTestDict(testDict, handle):
FILE: Project-4/textDisplay.py
class NullGraphics (line 26) | class NullGraphics:
method initialize (line 27) | def initialize(self, state, isBlue = False):
method update (line 30) | def update(self, state):
method checkNullDisplay (line 33) | def checkNullDisplay(self):
method pause (line 36) | def pause(self):
method draw (line 39) | def draw(self, state):
method updateDistributions (line 42) | def updateDistributions(self, dist):
method finish (line 45) | def finish(self):
class PacmanGraphics (line 48) | class PacmanGraphics:
method __init__ (line 49) | def __init__(self, speed=None):
method initialize (line 54) | def initialize(self, state, isBlue = False):
method update (line 60) | def update(self, state):
method pause (line 74) | def pause(self):
method draw (line 77) | def draw(self, state):
method finish (line 80) | def finish(self):
FILE: Project-4/trackingTestClasses.py
class GameScoreTest (line 40) | class GameScoreTest(testClasses.TestCase):
method __init__ (line 42) | def __init__(self, question, testDict):
method execute (line 55) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 74) | def writeSolution(self, moduleDict, filePath):
method createPublicVersion (line 79) | def createPublicVersion(self):
class ZeroWeightTest (line 82) | class ZeroWeightTest(testClasses.TestCase):
method __init__ (line 84) | def __init__(self, question, testDict):
method execute (line 95) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 115) | def writeSolution(self, moduleDict, filePath):
method createPublicVersion (line 120) | def createPublicVersion(self):
class DoubleInferenceAgentTest (line 124) | class DoubleInferenceAgentTest(testClasses.TestCase):
method __init__ (line 126) | def __init__(self, question, testDict):
method execute (line 140) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 170) | def writeSolution(self, moduleDict, filePath):
method createPublicVersion (line 199) | def createPublicVersion(self):
function run (line 203) | def run(layout_str, pac, ghosts, disp, nGames = 1, name = 'games', maxMo...
class InferenceAgent (line 222) | class InferenceAgent(bustersAgents.BustersAgent):
method __init__ (line 225) | def __init__( self, inference, ghostAgents, seed, elapse=True, observe...
method final (line 236) | def final(self, gameState):
method registerInitialState (line 248) | def registerInitialState(self, gameState):
method getAction (line 255) | def getAction(self, gameState):
class ZeroWeightAgent (line 274) | class ZeroWeightAgent(bustersAgents.BustersAgent):
method __init__ (line 277) | def __init__( self, inference, ghostAgents, grades, seed, disp, elapse...
method final (line 287) | def final(self, gameState):
method registerInitialState (line 290) | def registerInitialState(self, gameState):
method getAction (line 296) | def getAction(self, gameState):
method checkReset (line 314) | def checkReset(self, newBeliefs, oldBeliefs):
method getReset (line 321) | def getReset(self):
class DoubleInferenceAgent (line 325) | class DoubleInferenceAgent(bustersAgents.BustersAgent):
method __init__ (line 328) | def __init__( self, inference, refSolution, ghostAgents, grades, seed,...
method final (line 342) | def final(self, gameState):
method registerInitialState (line 356) | def registerInitialState(self, gameState):
method getAction (line 365) | def getAction(self, gameState):
method distCompare (line 381) | def distCompare(self, dist, refDist):
class SeededRandomGhostAgent (line 410) | class SeededRandomGhostAgent(Agent):
method __init__ (line 411) | def __init__(self, index):
method getAction (line 414) | def getAction(self, state):
method getDistribution (line 424) | def getDistribution( self, state ):
method sample (line 430) | def sample(self, distribution, values = None):
class GoSouthAgent (line 444) | class GoSouthAgent(Agent):
method __init__ (line 445) | def __init__(self, index):
method getAction (line 448) | def getAction(self, state):
method getDistribution (line 461) | def getDistribution( self, state ):
method sample (line 470) | def sample(self, distribution, values = None):
class DispersingSeededGhost (line 484) | class DispersingSeededGhost( Agent):
method __init__ (line 486) | def __init__( self, index, spreadProb=0.5):
method getAction (line 490) | def getAction(self, state):
method getDistribution (line 498) | def getDistribution( self, state ):
method sample (line 527) | def sample(self, distribution, values = None):
FILE: Project-4/util.py
class FixedRandom (line 21) | class FixedRandom:
method __init__ (line 22) | def __init__(self):
class Stack (line 120) | class Stack:
method __init__ (line 122) | def __init__(self):
method push (line 125) | def push(self,item):
method pop (line 129) | def pop(self):
method isEmpty (line 133) | def isEmpty(self):
class Queue (line 137) | class Queue:
method __init__ (line 139) | def __init__(self):
method push (line 142) | def push(self,item):
method pop (line 146) | def pop(self):
method isEmpty (line 153) | def isEmpty(self):
class PriorityQueue (line 157) | class PriorityQueue:
method __init__ (line 168) | def __init__(self):
method push (line 172) | def push(self, item, priority):
method pop (line 180) | def pop(self):
method isEmpty (line 185) | def isEmpty(self):
class PriorityQueueWithFunction (line 188) | class PriorityQueueWithFunction(PriorityQueue):
method __init__ (line 195) | def __init__(self, priorityFunction):
method push (line 200) | def push(self, item):
function manhattanDistance (line 205) | def manhattanDistance( xy1, xy2 ):
class Counter (line 215) | class Counter(dict):
method __getitem__ (line 255) | def __getitem__(self, idx):
method incrementAll (line 259) | def incrementAll(self, keys, count):
method argMax (line 273) | def argMax(self):
method sortedKeys (line 283) | def sortedKeys(self):
method totalCount (line 300) | def totalCount(self):
method normalize (line 306) | def normalize(self):
method divideAll (line 318) | def divideAll(self, divisor):
method copy (line 326) | def copy(self):
method __mul__ (line 332) | def __mul__(self, y ):
method __radd__ (line 358) | def __radd__(self, y):
method __add__ (line 376) | def __add__( self, y ):
method __sub__ (line 402) | def __sub__( self, y ):
function raiseNotDefined (line 428) | def raiseNotDefined():
function normalize (line 436) | def normalize(vectorOrCounter):
function nSample (line 455) | def nSample(distribution, values, n):
function sample (line 471) | def sample(distribution, values = None):
function sampleFromCounter (line 485) | def sampleFromCounter(ctr):
function getProbability (line 489) | def getProbability(value, distribution, values):
function flipCoin (line 500) | def flipCoin( p ):
function chooseFromDistribution (line 504) | def chooseFromDistribution( distribution ):
function nearestPoint (line 514) | def nearestPoint( pos ):
function sign (line 524) | def sign( x ):
function arrayInvert (line 533) | def arrayInvert(array):
function matrixAsList (line 543) | def matrixAsList( matrix, value = True ):
function lookup (line 555) | def lookup(name, namespace):
function pause (line 573) | def pause():
class TimeoutFunctionException (line 591) | class TimeoutFunctionException(Exception):
class TimeoutFunction (line 596) | class TimeoutFunction:
method __init__ (line 597) | def __init__(self, function, timeout):
method handle_timeout (line 601) | def handle_timeout(self, signum, frame):
method __call__ (line 604) | def __call__(self, *args, **keyArgs):
class WritableNull (line 630) | class WritableNull:
method write (line 631) | def write(self, string):
function mutePrint (line 634) | def mutePrint():
function unmutePrint (line 645) | def unmutePrint():
FILE: Project-5/answers.py
function q2 (line 15) | def q2():
FILE: Project-5/autograder.py
function readCommand (line 31) | def readCommand(argv):
function confirmGenerate (line 83) | def confirmGenerate():
function setModuleName (line 100) | def setModuleName(module, filename):
function loadModuleString (line 118) | def loadModuleString(moduleSource):
function loadModuleFile (line 131) | def loadModuleFile(moduleName, filePath):
function readFile (line 136) | def readFile(path, root=""):
function splitStrings (line 173) | def splitStrings(d):
function printTest (line 184) | def printTest(testDict, solutionDict):
function runTest (line 194) | def runTest(testName, moduleDict, printTestCase=False, display=None):
function getDepends (line 219) | def getDepends(testParser, testRoot, question):
function getTestSubdirs (line 230) | def getTestSubdirs(testParser, testRoot, questionToGrade):
function evaluate (line 243) | def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR...
function getDisplay (line 310) | def getDisplay(graphicsByDefault, options=None):
FILE: Project-5/classificationAgents.py
class DummyOptions (line 37) | class DummyOptions:
method __init__ (line 38) | def __init__(self):
class ClassifierAgent (line 48) | class ClassifierAgent(Agent):
method __init__ (line 49) | def __init__(self, trainingData=None, validationData=None, classifierT...
method getAction (line 66) | def getAction(self, state):
function scoreEvaluation (line 74) | def scoreEvaluation(state):
FILE: Project-5/classificationMethod.py
class ClassificationMethod (line 17) | class ClassificationMethod:
method __init__ (line 29) | def __init__(self, legalLabels):
method train (line 37) | def train(self, trainingData, trainingLabels, validationData, validati...
method classify (line 54) | def classify(self, data):
FILE: Project-5/classificationTestClasses.py
function readDigitData (line 47) | def readDigitData(trainingSize=100, testSize=100):
function readSuicideData (line 66) | def readSuicideData(trainingSize=100, testSize=100):
function readContestData (line 76) | def readContestData(trainingSize=100, testSize=100):
function tinyDataSet (line 93) | def tinyDataSet():
function tinyDataSetPeceptronAndMira (line 113) | def tinyDataSetPeceptronAndMira():
function getAccuracy (line 155) | def getAccuracy(data, classifier, featureFunction=dataClassifier.basicFe...
class GradeClassifierTest (line 170) | class GradeClassifierTest(testClasses.TestCase):
method __init__ (line 172) | def __init__(self, question, testDict):
method grade_classifier (line 190) | def grade_classifier(self, moduleDict):
method execute (line 208) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 238) | def writeSolution(self, moduleDict, filePath):
class MultipleChoiceTest (line 252) | class MultipleChoiceTest(testClasses.TestCase):
method __init__ (line 254) | def __init__(self, question, testDict):
method execute (line 259) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 269) | def writeSolution(self, moduleDict, filePath):
FILE: Project-5/dataClassifier.py
function basicFeatureExtractorDigit (line 35) | def basicFeatureExtractorDigit(datum):
function basicFeatureExtractorFace (line 51) | def basicFeatureExtractorFace(datum):
function enhancedFeatureExtractorDigit (line 67) | def enhancedFeatureExtractorDigit(datum):
function basicFeatureExtractorPacman (line 137) | def basicFeatureExtractorPacman(state):
function enhancedFeatureExtractorPacman (line 155) | def enhancedFeatureExtractorPacman(state):
function enhancedPacmanFeatures (line 170) | def enhancedPacmanFeatures(state, action):
function contestFeatureExtractorDigit (line 206) | def contestFeatureExtractorDigit(datum):
function enhancedFeatureExtractorFace (line 213) | def enhancedFeatureExtractorFace(datum):
function analysis (line 221) | def analysis(classifier, guesses, testLabels, testData, rawTestData, pri...
class ImagePrinter (line 261) | class ImagePrinter:
method __init__ (line 262) | def __init__(self, width, height):
method printImage (line 266) | def printImage(self, pixels):
function default (line 289) | def default(str):
function readCommand (line 307) | def readCommand( argv ):
function runClassifier (line 438) | def runClassifier(args, options):
FILE: Project-5/game.py
class Agent (line 32) | class Agent:
method __init__ (line 39) | def __init__(self, index=0):
method getAction (line 42) | def getAction(self, state):
class Directions (line 49) | class Directions:
class Configuration (line 70) | class Configuration:
method __init__ (line 79) | def __init__(self, pos, direction):
method getPosition (line 83) | def getPosition(self):
method getDirection (line 86) | def getDirection(self):
method isInteger (line 89) | def isInteger(self):
method __eq__ (line 93) | def __eq__(self, other):
method __hash__ (line 97) | def __hash__(self):
method __str__ (line 102) | def __str__(self):
method generateSuccessor (line 105) | def generateSuccessor(self, vector):
class AgentState (line 120) | class AgentState:
method __init__ (line 125) | def __init__( self, startConfiguration, isPacman ):
method __str__ (line 133) | def __str__( self ):
method __eq__ (line 139) | def __eq__( self, other ):
method __hash__ (line 144) | def __hash__(self):
method copy (line 147) | def copy( self ):
method getPosition (line 155) | def getPosition(self):
method getDirection (line 159) | def getDirection(self):
class Grid (line 162) | class Grid:
method __init__ (line 170) | def __init__(self, width, height, initialValue=False, bitRepresentatio...
method __getitem__ (line 180) | def __getitem__(self, i):
method __setitem__ (line 183) | def __setitem__(self, key, item):
method __str__ (line 186) | def __str__(self):
method __eq__ (line 191) | def __eq__(self, other):
method __hash__ (line 195) | def __hash__(self):
method copy (line 206) | def copy(self):
method deepCopy (line 211) | def deepCopy(self):
method shallowCopy (line 214) | def shallowCopy(self):
method count (line 219) | def count(self, item =True ):
method asList (line 222) | def asList(self, key = True):
method packBits (line 229) | def packBits(self):
method _cellIndexToPosition (line 248) | def _cellIndexToPosition(self, index):
method _unpackBits (line 253) | def _unpackBits(self, bits):
method _unpackInt (line 265) | def _unpackInt(self, packed, size):
function reconstituteGrid (line 277) | def reconstituteGrid(bitRep):
class Actions (line 287) | class Actions:
method reverseDirection (line 302) | def reverseDirection(action):
method vectorToDirection (line 314) | def vectorToDirection(vector):
method directionToVector (line 327) | def directionToVector(direction, speed = 1.0):
method getPossibleActions (line 332) | def getPossibleActions(config, walls):
method getLegalNeighbors (line 351) | def getLegalNeighbors(position, walls):
method getSuccessor (line 365) | def getSuccessor(position, action):
class GameStateData (line 371) | class GameStateData:
method __init__ (line 375) | def __init__( self, prevState = None ):
method deepCopy (line 395) | def deepCopy( self ):
method copyAgentStates (line 405) | def copyAgentStates( self, agentStates ):
method __eq__ (line 411) | def __eq__( self, other ):
method __hash__ (line 423) | def __hash__( self ):
method __str__ (line 435) | def __str__( self ):
method _foodWallStr (line 460) | def _foodWallStr( self, hasFood, hasWall ):
method _pacStr (line 468) | def _pacStr( self, dir ):
method _ghostStr (line 477) | def _ghostStr( self, dir ):
method initialize (line 487) | def initialize( self, layout, numGhostAgents ):
class Game (line 513) | class Game:
method __init__ (line 518) | def __init__( self, agents, display, rules, startingIndex=0, muteAgent...
method getProgress (line 534) | def getProgress(self):
method _agentCrash (line 540) | def _agentCrash( self, agentIndex, quiet=False):
method mute (line 550) | def mute(self, agentIndex):
method unmute (line 559) | def unmute(self):
method run (line 567) | def run( self ):
FILE: Project-5/ghostAgents.py
class GhostAgent (line 22) | class GhostAgent( Agent ):
method __init__ (line 23) | def __init__( self, index ):
method getAction (line 26) | def getAction( self, state ):
method getDistribution (line 33) | def getDistribution(self, state):
class RandomGhost (line 37) | class RandomGhost( GhostAgent ):
method getDistribution (line 39) | def getDistribution( self, state ):
class DirectionalGhost (line 45) | class DirectionalGhost( GhostAgent ):
method __init__ (line 47) | def __init__( self, index, prob_attack=0.8, prob_scaredFlee=0.8 ):
method getDistribution (line 52) | def getDistribution( self, state ):
FILE: Project-5/grading.py
class Grades (line 25) | class Grades:
method __init__ (line 27) | def __init__(self, projectName, questionsAndMaxesList, edxOutput=False...
method addPrereq (line 48) | def addPrereq(self, question, prereq):
method grade (line 51) | def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
method addExceptionMessage (line 139) | def addExceptionMessage(self, q, inst, traceback):
method addErrorHints (line 149) | def addErrorHints(self, exceptionMap, errorInstance, questionNum):
method produceOutput (line 171) | def produceOutput(self):
method fail (line 227) | def fail(self, message, raw=False):
method assignZeroCredit (line 233) | def assignZeroCredit(self):
method addPoints (line 236) | def addPoints(self, amt):
method deductPoints (line 239) | def deductPoints(self, amt):
method assignFullCredit (line 242) | def assignFullCredit(self, message="", raw=False):
method addMessage (line 247) | def addMessage(self, message, raw=False):
method addMessageToEmail (line 256) | def addMessageToEmail(self, message):
class Counter (line 267) | class Counter(dict):
method __getitem__ (line 271) | def __getitem__(self, idx):
method totalCount (line 277) | def totalCount(self):
FILE: Project-5/graphicsDisplay.py
class InfoPane (line 82) | class InfoPane:
method __init__ (line 83) | def __init__(self, layout, gridSize):
method toScreen (line 92) | def toScreen(self, pos, y = None):
method drawPane (line 105) | def drawPane(self):
method initializeGhostDistances (line 108) | def initializeGhostDistances(self, distances):
method updateScore (line 121) | def updateScore(self, score):
method setTeam (line 124) | def setTeam(self, isBlue):
method updateGhostDistances (line 129) | def updateGhostDistances(self, distances):
method drawGhost (line 136) | def drawGhost(self):
method drawPacman (line 139) | def drawPacman(self):
method drawWarning (line 142) | def drawWarning(self):
method clearIcon (line 145) | def clearIcon(self):
method updateMessage (line 148) | def updateMessage(self, message):
method clearMessage (line 151) | def clearMessage(self):
class PacmanGraphics (line 155) | class PacmanGraphics:
method __init__ (line 156) | def __init__(self, zoom=1.0, frameTime=0.0, capture=False):
method checkNullDisplay (line 165) | def checkNullDisplay(self):
method initialize (line 168) | def initialize(self, state, isBlue = False):
method startGraphics (line 180) | def startGraphics(self, state):
method drawDistributions (line 189) | def drawDistributions(self, state):
method drawStaticObjects (line 204) | def drawStaticObjects(self, state):
method drawAgentObjects (line 211) | def drawAgentObjects(self, state):
method swapImages (line 222) | def swapImages(self, agentIndex, newState):
method update (line 236) | def update(self, newState):
method make_window (line 256) | def make_window(self, width, height):
method drawPacman (line 267) | def drawPacman(self, pacman, index):
method getEndpoints (line 286) | def getEndpoints(self, direction, position=(0,0)):
method movePacman (line 302) | def movePacman(self, position, direction, image):
method animatePacman (line 309) | def animatePacman(self, pacman, prevPacman, image):
method getGhostColor (line 329) | def getGhostColor(self, ghost, ghostIndex):
method drawGhost (line 335) | def drawGhost(self, ghost, agentIndex):
method moveEyes (line 371) | def moveEyes(self, pos, dir, eyes):
method moveGhost (line 388) | def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
method getPosition (line 405) | def getPosition(self, agentState):
method getDirection (line 409) | def getDirection(self, agentState):
method finish (line 413) | def finish(self):
method to_screen (line 416) | def to_screen(self, point):
method to_screen2 (line 424) | def to_screen2(self, point):
method drawWalls (line 431) | def drawWalls(self, wallMatrix):
method isWall (line 517) | def isWall(self, x, y, walls):
method drawFood (line 524) | def drawFood(self, foodMatrix ):
method drawCapsules (line 544) | def drawCapsules(self, capsules ):
method removeFood (line 556) | def removeFood(self, cell, foodImages ):
method removeCapsule (line 560) | def removeCapsule(self, cell, capsuleImages ):
method drawExpandedCells (line 564) | def drawExpandedCells(self, cells):
method clearExpandedCells (line 583) | def clearExpandedCells(self):
method updateDistributions (line 589) | def updateDistributions(self, distributions):
class FirstPersonPacmanGraphics (line 611) | class FirstPersonPacmanGraphics(PacmanGraphics):
method __init__ (line 612) | def __init__(self, zoom = 1.0, showGhosts = True, capture = False, fra...
method initialize (line 617) | def initialize(self, state, isBlue = False):
method lookAhead (line 634) | def lookAhead(self, config, state):
method getGhostColor (line 648) | def getGhostColor(self, ghost, ghostIndex):
method getPosition (line 651) | def getPosition(self, ghostState):
function add (line 657) | def add(x, y):
function saveFrame (line 672) | def saveFrame():
FILE: Project-5/graphicsUtils.py
function formatColor (line 35) | def formatColor(r, g, b):
function colorToVector (line 38) | def colorToVector(color):
function sleep (line 47) | def sleep(secs):
function begin_graphics (line 56) | def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), ti...
function _leftclick (line 101) | def _leftclick(event):
function _rightclick (line 105) | def _rightclick(event):
function _ctrl_leftclick (line 109) | def _ctrl_leftclick(event):
function wait_for_click (line 113) | def wait_for_click():
function draw_background (line 132) | def draw_background():
function _destroy_window (line 136) | def _destroy_window(event=None):
function end_graphics (line 143) | def end_graphics():
function clear_screen (line 158) | def clear_screen(background=None):
function polygon (line 164) | def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, ...
function square (line 176) | def square(pos, r, color, filled=1, behind=0):
function circle (line 181) | def circle(pos, r, outlineColor, fillColor, endpoints=None, style='piesl...
function image (line 194) | def image(pos, file="../../blueghost.gif"):
function refresh (line 200) | def refresh():
function moveCircle (line 203) | def moveCircle(id, pos, r, endpoints=None):
function edit (line 220) | def edit(id, *args):
function text (line 223) | def text(pos, color, contents, font='Helvetica', size=12, style='normal'...
function changeText (line 229) | def changeText(id, newText, font=None, size=12, style='normal'):
function changeColor (line 234) | def changeColor(id, newColor):
function line (line 237) | def line(here, there, color=formatColor(0, 0, 0), width=2):
function _keypress (line 254) | def _keypress(event):
function _keyrelease (line 262) | def _keyrelease(event):
function remap_arrows (line 271) | def remap_arrows(event):
function _clear_keys (line 284) | def _clear_keys(event=None):
function keys_pressed (line 290) | def keys_pressed(d_o_e=Tkinter.tkinter.dooneevent,
function keys_waiting (line 297) | def keys_waiting():
function wait_for_keys (line 305) | def wait_for_keys():
function remove_from_screen (line 312) | def remove_from_screen(x,
function _adjust_coords (line 318) | def _adjust_coords(coord_list, x, y):
function move_to (line 324) | def move_to(object, x, y=None,
function move_by (line 346) | def move_by(object, x, y=None,
function writePostscript (line 369) | def writePostscript(filename):
FILE: Project-5/keyboardAgents.py
class KeyboardAgent (line 19) | class KeyboardAgent(Agent):
method __init__ (line 30) | def __init__( self, index = 0 ):
method getAction (line 36) | def getAction( self, state):
method getMove (line 59) | def getMove(self, legal):
class KeyboardAgent2 (line 67) | class KeyboardAgent2(KeyboardAgent):
method getMove (line 78) | def getMove(self, legal):
FILE: Project-5/layout.py
class Layout (line 22) | class Layout:
method __init__ (line 27) | def __init__(self, layoutText):
method getNumGhosts (line 40) | def getNumGhosts(self):
method initializeVisibilityMatrix (line 43) | def initializeVisibilityMatrix(self):
method isWall (line 64) | def isWall(self, pos):
method getRandomLegalPosition (line 68) | def getRandomLegalPosition(self):
method getRandomCorner (line 76) | def getRandomCorner(self):
method getFurthestCorner (line 80) | def getFurthestCorner(self, pacPos):
method isVisibleFrom (line 85) | def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
method __str__ (line 89) | def __str__(self):
method deepCopy (line 92) | def deepCopy(self):
method processLayoutText (line 95) | def processLayoutText(self, layoutText):
method processLayoutChar (line 116) | def processLayoutChar(self, x, y, layoutChar):
function getLayout (line 131) | def getLayout(name, back = 2):
function tryToLoad (line 145) | def tryToLoad(fullname):
FILE: Project-5/mira.py
class MiraClassifier (line 19) | class MiraClassifier:
method __init__ (line 26) | def __init__( self, legalLabels, max_iterations):
method initializeWeightsToZero (line 35) | def initializeWeightsToZero(self):
method train (line 41) | def train(self, trainingData, trainingLabels, validationData, validati...
method trainAndTune (line 53) | def trainAndTune(self, trainingData, trainingLabels, validationData, v...
method classify (line 90) | def classify(self, data ):
FILE: Project-5/mostFrequent.py
class MostFrequentClassifier (line 18) | class MostFrequentClassifier(classificationMethod.ClassificationMethod):
method __init__ (line 24) | def __init__(self, legalLabels):
method train (line 28) | def train(self, data, labels, validationData, validationLabels):
method classify (line 36) | def classify(self, testData):
FILE: Project-5/naiveBayes.py
class NaiveBayesClassifier (line 19) | class NaiveBayesClassifier(classificationMethod.ClassificationMethod):
method __init__ (line 26) | def __init__(self, legalLabels):
method setSmoothing (line 32) | def setSmoothing(self, k):
method train (line 39) | def train(self, trainingData, trainingLabels, validationData, validati...
method trainAndTune (line 55) | def trainAndTune(self, trainingData, trainingLabels, validationData, v...
method classify (line 126) | def classify(self, testData):
method calculateLogJointProbabilities (line 140) | def calculateLogJointProbabilities(self, datum):
method findHighOddsFeatures (line 161) | def findHighOddsFeatures(self, label1, label2):
FILE: Project-5/pacman.py
class GameState (line 55) | class GameState:
method getAndResetExplored (line 76) | def getAndResetExplored():
method getLegalActions (line 82) | def getLegalActions( self, agentIndex=0 ):
method generateSuccessor (line 94) | def generateSuccessor( self, agentIndex, action):
method getLegalPacmanActions (line 127) | def getLegalPacmanActions( self ):
method generatePacmanSuccessor (line 130) | def generatePacmanSuccessor( self, action ):
method getPacmanState (line 136) | def getPacmanState( self ):
method getPacmanPosition (line 145) | def getPacmanPosition( self ):
method getGhostStates (line 148) | def getGhostStates( self ):
method getGhostState (line 151) | def getGhostState( self, agentIndex ):
method getGhostPosition (line 156) | def getGhostPosition( self, agentIndex ):
method getGhostPositions (line 161) | def getGhostPositions(self):
method getNumAgents (line 164) | def getNumAgents( self ):
method getScore (line 167) | def getScore( self ):
method getCapsules (line 170) | def getCapsules(self):
method getNumFood (line 176) | def getNumFood( self ):
method getFood (line 179) | def getFood(self):
method getWalls (line 191) | def getWalls(self):
method hasFood (line 203) | def hasFood(self, x, y):
method hasWall (line 206) | def hasWall(self, x, y):
method isLose (line 209) | def isLose( self ):
method isWin (line 212) | def isWin( self ):
method __init__ (line 220) | def __init__( self, prevState = None ):
method deepCopy (line 229) | def deepCopy( self ):
method __eq__ (line 234) | def __eq__( self, other ):
method __hash__ (line 240) | def __hash__( self ):
method __str__ (line 246) | def __str__( self ):
method initialize (line 250) | def initialize( self, layout, numGhostAgents=1000 ):
class ClassicGameRules (line 266) | class ClassicGameRules:
method __init__ (line 271) | def __init__(self, timeout=30):
method newGame (line 274) | def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = ...
method process (line 284) | def process(self, state, game):
method win (line 291) | def win( self, state, game ):
method lose (line 295) | def lose( self, state, game ):
method getProgress (line 299) | def getProgress(self, game):
method agentCrash (line 302) | def agentCrash(self, game, agentIndex):
method getMaxTotalTime (line 308) | def getMaxTotalTime(self, agentIndex):
method getMaxStartupTime (line 311) | def getMaxStartupTime(self, agentIndex):
method getMoveWarningTime (line 314) | def getMoveWarningTime(self, agentIndex):
method getMoveTimeout (line 317) | def getMoveTimeout(self, agentIndex):
method getMaxTimeWarnings (line 320) | def getMaxTimeWarnings(self, agentIndex):
class PacmanRules (line 323) | class PacmanRules:
method getLegalActions (line 330) | def getLegalActions( state ):
method applyAction (line 337) | def applyAction( state, action ):
method consume (line 359) | def consume( position, state ):
class GhostRules (line 381) | class GhostRules:
method getLegalActions (line 386) | def getLegalActions( state, ghostIndex ):
method applyAction (line 401) | def applyAction( state, action, ghostIndex):
method decrementTimer (line 414) | def decrementTimer( ghostState):
method checkDeath (line 421) | def checkDeath( state, agentIndex):
method collide (line 436) | def collide( state, ghostState, agentIndex):
method canKill (line 449) | def canKill( pacmanPosition, ghostPosition ):
method placeGhost (line 453) | def placeGhost(state, ghostState):
function default (line 461) | def default(str):
function parseAgentArgs (line 464) | def parseAgentArgs(str):
function readCommand (line 476) | def readCommand( argv ):
function loadAgent (line 587) | def loadAgent(pacman, nographics):
function replayGame (line 610) | def replayGame( layout, actions, display ):
function runGames (line 628) | def runGames( layout, pacman, ghosts, display, numGames, record, numTrai...
FILE: Project-5/pacmanAgents.py
class LeftTurnAgent (line 21) | class LeftTurnAgent(game.Agent):
method getAction (line 24) | def getAction(self, state):
class GreedyAgent (line 35) | class GreedyAgent(Agent):
method __init__ (line 36) | def __init__(self, evalFn="scoreEvaluation"):
method getAction (line 40) | def getAction(self, state):
function scoreEvaluation (line 51) | def scoreEvaluation(state):
FILE: Project-5/perceptron.py
class PerceptronClassifier (line 19) | class PerceptronClassifier:
method __init__ (line 26) | def __init__( self, legalLabels, max_iterations):
method setWeights (line 34) | def setWeights(self, weights):
method train (line 38) | def train( self, trainingData, trainingLabels, validationData, validat...
method classify (line 63) | def classify(self, data ):
method findHighWeightFeatures (line 79) | def findHighWeightFeatures(self, label):
FILE: Project-5/perceptron_pacman.py
class PerceptronClassifierPacman (line 23) | class PerceptronClassifierPacman(PerceptronClassifier):
method __init__ (line 24) | def __init__(self, legalLabels, maxIterations):
method classify (line 28) | def classify(self, data ):
method train (line 44) | def train( self, trainingData, trainingLabels, validationData, validat...
FILE: Project-5/samples.py
class Datum (line 23) | class Datum:
method __init__ (line 59) | def __init__(self, data,width,height):
method getPixel (line 71) | def getPixel(self, column, row):
method getPixels (line 77) | def getPixels(self):
method getAsciiString (line 83) | def getAsciiString(self):
method __str__ (line 94) | def __str__(self):
function loadDataFile (line 101) | def loadDataFile(filename, n,width,height):
function readlines (line 125) | def readlines(filename):
function loadLabelsFile (line 133) | def loadLabelsFile(filename, n):
function loadPacmanStatesFile (line 145) | def loadPacmanStatesFile(filename, n):
function loadPacmanData (line 156) | def loadPacmanData(filename, n):
function asciiGrayscaleConversionFunction (line 163) | def asciiGrayscaleConversionFunction(value):
function IntegerConversionFunction (line 174) | def IntegerConversionFunction(character):
function convertToInteger (line 185) | def convertToInteger(data):
function _test (line 196) | def _test():
FILE: Project-5/testClasses.py
class Question (line 24) | class Question(object):
method raiseNotDefined (line 26) | def raiseNotDefined(self):
method __init__ (line 30) | def __init__(self, questionDict, display):
method getDisplay (line 35) | def getDisplay(self):
method getMaxPoints (line 38) | def getMaxPoints(self):
method addTestCase (line 43) | def addTestCase(self, testCase, thunk):
method execute (line 46) | def execute(self, grades):
class PassAllTestsQuestion (line 50) | class PassAllTestsQuestion(Question):
method execute (line 52) | def execute(self, grades):
class HackedPartialCreditQuestion (line 67) | class HackedPartialCreditQuestion(Question):
method execute (line 69) | def execute(self, grades):
class Q6PartialCreditQuestion (line 89) | class Q6PartialCreditQuestion(Question):
method execute (line 93) | def execute(self, grades):
class PartialCreditQuestion (line 102) | class PartialCreditQuestion(Question):
method execute (line 106) | def execute(self, grades):
class NumberPassedQuestion (line 117) | class NumberPassedQuestion(Question):
method execute (line 120) | def execute(self, grades):
class TestCase (line 128) | class TestCase(object):
method raiseNotDefined (line 130) | def raiseNotDefined(self):
method getPath (line 134) | def getPath(self):
method __init__ (line 137) | def __init__(self, question, testDict):
method __str__ (line 143) | def __str__(self):
method execute (line 146) | def execute(self, grades, moduleDict, solutionDict):
method writeSolution (line 149) | def writeSolution(self, moduleDict, filePath):
method testPass (line 159) | def testPass(self, grades):
method testFail (line 165) | def testFail(self, grades):
method testPartial (line 173) | def testPartial(self, grades, points, maxPoints):
method addMessage (line 187) | def addMessage(self, message):
FILE: Project-5/testParser.py
class TestParser (line 18) | class TestParser(object):
method __init__ (line 20) | def __init__(self, path):
method removeComments (line 24) | def removeComments(self, rawlines):
method parse (line 35) | def parse(self):
function emitTestDict (line 76) | def emitTestDict(testDict, handle):
FILE: Project-5/textDisplay.py
class NullGraphics (line 26) | class NullGraphics:
method initialize (line 27) | def initialize(self, state, isBlue = False):
method update (line 30) | def update(self, state):
method checkNullDisplay (line 33) | def checkNullDisplay(self):
method pause (line 36) | def pause(self):
method draw (line 39) | def draw(self, state):
method updateDistributions (line 42) | def updateDistributions(self, dist):
method finish (line 45) | def finish(self):
class PacmanGraphics (line 48) | class PacmanGraphics:
method __init__ (line 49) | def __init__(self, speed=None):
method initialize (line 54) | def initialize(self, state, isBlue = False):
method update (line 60) | def update(self, state):
method pause (line 74) | def pause(self):
method draw (line 77) | def draw(self, state):
method finish (line 80) | def finish(self):
FILE: Project-5/util.py
class FixedRandom (line 21) | class FixedRandom:
method __init__ (line 22) | def __init__(self):
class Stack (line 120) | class Stack:
method __init__ (line 122) | def __init__(self):
method push (line 125) | def push(self,item):
method pop (line 129) | def pop(self):
method isEmpty (line 133) | def isEmpty(self):
class Queue (line 137) | class Queue:
method __init__ (line 139) | def __init__(self):
method push (line 142) | def push(self,item):
method pop (line 146) | def pop(self):
method isEmpty (line 153) | def isEmpty(self):
class PriorityQueue (line 157) | class PriorityQueue:
method __init__ (line 168) | def __init__(self):
method push (line 172) | def push(self, item, priority):
method pop (line 180) | def pop(self):
method isEmpty (line 185) | def isEmpty(self):
class PriorityQueueWithFunction (line 188) | class PriorityQueueWithFunction(PriorityQueue):
method __init__ (line 195) | def __init__(self, priorityFunction):
method push (line 200) | def push(self, item):
function manhattanDistance (line 205) | def manhattanDistance( xy1, xy2 ):
class Counter (line 215) | class Counter(dict):
method __getitem__ (line 255) | def __getitem__(self, idx):
method incrementAll (line 259) | def incrementAll(self, keys, count):
method argMax (line 273) | def argMax(self):
method sortedKeys (line 283) | def sortedKeys(self):
method totalCount (line 300) | def totalCount(self):
method normalize (line 306) | def normalize(self):
method divideAll (line 318) | def divideAll(self, divisor):
method copy (line 326) | def copy(self):
method __mul__ (line 332) | def __mul__(self, y ):
method __radd__ (line 358) | def __radd__(self, y):
method __add__ (line 376) | def __add__( self, y ):
method __sub__ (line 402) | def __sub__( self, y ):
function raiseNotDefined (line 428) | def raiseNotDefined():
function normalize (line 436) | def normalize(vectorOrCounter):
function nSample (line 455) | def nSample(distribution, values, n):
function sample (line 471) | def sample(distribution, values = None):
function sampleFromCounter (line 485) | def sampleFromCounter(ctr):
function getProbability (line 489) | def getProbability(value, distribution, values):
function flipCoin (line 500) | def flipCoin( p ):
function chooseFromDistribution (line 504) | def chooseFromDistribution( distribution ):
function nearestPoint (line 514) | def nearestPoint( pos ):
function sign (line 524) | def sign( x ):
function arrayInvert (line 533) | def arrayInvert(array):
function matrixAsList (line 543) | def matrixAsList( matrix, value = True ):
function lookup (line 555) | def lookup(name, namespace):
function pause (line 573) | def pause():
class TimeoutFunctionException (line 591) | class TimeoutFunctionException(Exception):
class TimeoutFunction (line 596) | class TimeoutFunction:
method __init__ (line 597) | def __init__(self, function, timeout):
method handle_timeout (line 601) | def handle_timeout(self, signum, frame):
method __call__ (line 604) | def __call__(self, *args, **keyArgs):
class WritableNull (line 630) | class WritableNull:
method write (line 631) | def write(self, string):
function mutePrint (line 634) | def mutePrint():
function unmutePrint (line 645) | def unmutePrint():
Copy disabled (too large)
Download .json
Condensed preview — 671 files, each showing path, character count, and a content snippet. Download the .json file for the full structured content (43,403K chars).
[
{
"path": "Project-1/VERSION",
"chars": 8,
"preview": "v1.001\r\n"
},
{
"path": "Project-1/autograder.py",
"chars": 14027,
"preview": "# autograder.py\n# -------------\n# Licensing Information: You are free to use or extend these projects for\n# educational"
},
{
"path": "Project-1/commands.txt",
"chars": 1214,
"preview": "python pacman.py\npython pacman.py --layout testMaze --pacman GoWestAgent\npython pacman.py --layout tinyMaze --pacman GoW"
},
{
"path": "Project-1/eightpuzzle.py",
"chars": 8717,
"preview": "# eightpuzzle.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# education"
},
{
"path": "Project-1/game.py",
"chars": 25518,
"preview": "# game.py\n# -------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes pr"
},
{
"path": "Project-1/ghostAgents.py",
"chars": 3108,
"preview": "# ghostAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# education"
},
{
"path": "Project-1/grading.py",
"chars": 9271,
"preview": "# grading.py\n# ----------\n# Licensing Information: You are free to use or extend these projects for\n# educational purpo"
},
{
"path": "Project-1/graphicsDisplay.py",
"chars": 28031,
"preview": "# graphicsDisplay.py\n# ------------------\n# Licensing Information: You are free to use or extend these projects for\n# e"
},
{
"path": "Project-1/graphicsUtils.py",
"chars": 11785,
"preview": "# graphicsUtils.py\n# ----------------\n# Licensing Information: You are free to use or extend these projects for\n# educa"
},
{
"path": "Project-1/keyboardAgents.py",
"chars": 3045,
"preview": "# keyboardAgents.py\n# -----------------\n# Licensing Information: You are free to use or extend these projects for\n# edu"
},
{
"path": "Project-1/layout.py",
"chars": 5753,
"preview": "# layout.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purpose"
},
{
"path": "Project-1/layouts/bigCorners.lay",
"chars": 1405,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%. % %.%\n% %%%%% % %%% %%% %%%%%%% % %\n% "
},
{
"path": "Project-1/layouts/bigMaze.lay",
"chars": 1405,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % % % % % % %\n% %%%%%%% % %%% % %%% %%% %%%%%%% % %\n% "
},
{
"path": "Project-1/layouts/bigSafeSearch.lay",
"chars": 256,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%.%.........%% G % o%%%%.....%\n%.%.%%%%%%%.%%%%%% %%%%%%%.%%.%\n%............%...%......"
},
{
"path": "Project-1/layouts/bigSearch.lay",
"chars": 480,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%.....%.................%.....%\n%.%%%.%.%%%.%%%%%%%.%%%.%.....%\n%.%...%.%......%......%."
},
{
"path": "Project-1/layouts/boxSearch.lay",
"chars": 210,
"preview": "%%%%%%%%%%%%%%\n%. . . . . % %\n% % %\n%. . . . . %G%\n% % %\n%. . . . . % %\n% % %\n%. . . . . % %\n"
},
{
"path": "Project-1/layouts/capsuleClassic.lay",
"chars": 141,
"preview": "%%%%%%%%%%%%%%%%%%%\n%G. G ....%\n%.% % %%%%%% %.%%.%\n%.%o% % o% %.o%.%\n%.%%%.% %%% %..%.%\n%..... P %..%G%\n"
},
{
"path": "Project-1/layouts/contestClassic.lay",
"chars": 189,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%o...%........%...o%\n%.%%.%.%%..%%.%.%%.%\n%...... G GG%......%\n%.%.%%.%% %%%.%%.%.%\n%.%....% ooo%.%"
},
{
"path": "Project-1/layouts/contoursMaze.lay",
"chars": 241,
"preview": "%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% %\n% "
},
{
"path": "Project-1/layouts/greedySearch.lay",
"chars": 55,
"preview": "%%%%%%\n%....%\n% %%.%\n% %%.%\n%.P .%\n%.%%%%\n%....%\n%%%%%%"
},
{
"path": "Project-1/layouts/mediumClassic.lay",
"chars": 231,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%o...%........%....%\n%.%%.%.%%%%%%.%.%%.%\n%.%..............%.%\n%.%.%%.%% %%.%%.%.%\n%......%G G%.."
},
{
"path": "Project-1/layouts/mediumCorners.lay",
"chars": 433,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%. % % % %.%\n% % % %%%%%% %%%%%%% % %\n% % % % % "
},
{
"path": "Project-1/layouts/mediumDottedMaze.lay",
"chars": 666,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% P%\n% %%%%%%%%%%%%%%%%%%% %%% %%%%%%%% %\n% %% % "
},
{
"path": "Project-1/layouts/mediumMaze.lay",
"chars": 666,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% P%\n% %%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% %\n% %% % "
},
{
"path": "Project-1/layouts/mediumSafeSearch.lay",
"chars": 192,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%.% ....%% G %%%%%% o%%.%\n%.%o%%%%%%%.%%%%%%% %%%%%.%\n% %%%.%%%%%.%%%%%%%.%%%."
},
{
"path": "Project-1/layouts/mediumScaryMaze.lay",
"chars": 702,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% P%\n% %%%%%%%%%%%%%%%%%%% %%% %%%%%%%% %\n% %"
},
{
"path": "Project-1/layouts/mediumSearch.lay",
"chars": 256,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%............%%%%%............%\n%%%.%...%%%.........%.%...%.%%%\n%...%%%.%.%%%%.%.%%%%%%."
},
{
"path": "Project-1/layouts/minimaxClassic.lay",
"chars": 54,
"preview": "%%%%%%%%%\n%.P G% \n% %.%G%%% \n%G %%% \n%%%%%%%%%\n"
},
{
"path": "Project-1/layouts/oddSearch.lay",
"chars": 147,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%...%.........%%...%\n%.%.%.%%%%%%%%%%.%.%\n%..................%\n%%%%%%%%.%.%%%%%%%P%\n%%%%%%%%......."
},
{
"path": "Project-1/layouts/openClassic.lay",
"chars": 234,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%\n%.. P .... .... %\n%.. ... ... ... ... %\n%.. ... ... ... ... %\n%.. .... "
},
{
"path": "Project-1/layouts/openMaze.lay",
"chars": 873,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% P%\n% % %\n% "
},
{
"path": "Project-1/layouts/openSearch.lay",
"chars": 147,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%..................%\n%..................%\n%........P.........%\n%..................%\n%.............."
},
{
"path": "Project-1/layouts/originalClassic.lay",
"chars": 783,
"preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%............%%............%\n%.%%%%.%%%%%.%%.%%%%%.%%%%.%\n%o%%%%.%%%%%.%%.%%%%%.%%%%o%\n%.%%"
},
{
"path": "Project-1/layouts/smallClassic.lay",
"chars": 147,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%......%G G%......%\n%.%%...%% %%...%%.%\n%.%o.%........%.o%.%\n%.%%.%.%%%%%%.%.%%.%\n%........P....."
},
{
"path": "Project-1/layouts/smallMaze.lay",
"chars": 229,
"preview": "%%%%%%%%%%%%%%%%%%%%%%\n% %% % % %\n% %%%%%% % %%%%%% %\n%%%%%% P % %\n% % %%%%%% %% %%%%%\n% %%%"
},
{
"path": "Project-1/layouts/smallSafeSearch.lay",
"chars": 150,
"preview": "%%%%%%%%%\n%.. % G %\n%%% %%%%%\n% %\n%%%%%%% %\n% %\n% %%%%% %\n% % %\n%%%%% % %\n% %o%\n% %%%%%%%\n% .%\n"
},
{
"path": "Project-1/layouts/smallSearch.lay",
"chars": 105,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%. ...P .%\n%.%%.%%.%%.%%.%% %.%\n% %% %..... %.%\n%%%%%%%%%%%%%%%%%%%%\n"
},
{
"path": "Project-1/layouts/testClassic.lay",
"chars": 60,
"preview": "%%%%%\n% . %\n%.G.%\n% . %\n%. .%\n% %\n% .%\n% %\n%P .%\n%%%%%\n"
},
{
"path": "Project-1/layouts/testMaze.lay",
"chars": 33,
"preview": "%%%%%%%%%%\n%. P%\n%%%%%%%%%%\n"
},
{
"path": "Project-1/layouts/testSearch.lay",
"chars": 30,
"preview": "%%%%%\n%.P %\n%%% %\n%. %\n%%%%%\n"
},
{
"path": "Project-1/layouts/tinyCorners.lay",
"chars": 72,
"preview": "%%%%%%%%\n%. .%\n% P %\n% %%%% %\n% % %\n% % %%%%\n%.% .%\n%%%%%%%%\n"
},
{
"path": "Project-1/layouts/tinyMaze.lay",
"chars": 56,
"preview": "%%%%%%%\n% P%\n% %%% %\n% % %\n%% %%\n%. %%%%\n%%%%%%%\n"
},
{
"path": "Project-1/layouts/tinySafeSearch.lay",
"chars": 70,
"preview": "%%%%%%%%%\n% G %...%\n%%%%%%% %\n%Po %\n%.%%.%%.%\n%.%%....%\n%%%%%%%%%\n"
},
{
"path": "Project-1/layouts/tinySearch.lay",
"chars": 70,
"preview": "%%%%%%%%%\n%.. ..%\n%%%%.%% %\n% P %\n%.%% %%.%\n%.%. .%\n%%%%%%%%%\n"
},
{
"path": "Project-1/layouts/trappedClassic.lay",
"chars": 45,
"preview": "%%%%%%%%\n% P G%\n%G%%%%%%\n%.... %\n%%%%%%%%\n"
},
{
"path": "Project-1/layouts/trickyClassic.lay",
"chars": 273,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%o...%........%...o%\n%.%%.%.%%..%%.%.%%.%\n%.%.....%..%.....%.%\n%.%.%%.%% %%.%%.%.%\n%...... GGGG%.%"
},
{
"path": "Project-1/layouts/trickySearch.lay",
"chars": 147,
"preview": "%%%%%%%%%%%%%%%%%%%%\n%. ..% %\n%.%%.%%.%%.%%.%% % %\n% P % %\n%%%%%%%%%%%%%%%%%% %\n%..... "
},
{
"path": "Project-1/pacman.py",
"chars": 26331,
"preview": "# pacman.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purpose"
},
{
"path": "Project-1/pacmanAgents.py",
"chars": 2116,
"preview": "# pacmanAgents.py\n# ---------------\n# Licensing Information: You are free to use or extend these projects for\n# educati"
},
{
"path": "Project-1/projectParams.py",
"chars": 814,
"preview": "# projectParams.py\n# ----------------\n# Licensing Information: You are free to use or extend these projects for\n# educa"
},
{
"path": "Project-1/search.py",
"chars": 8488,
"preview": "# search.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purpose"
},
{
"path": "Project-1/searchAgents.py",
"chars": 22639,
"preview": "# searchAgents.py\n# ---------------\n# Licensing Information: You are free to use or extend these projects for\n# educati"
},
{
"path": "Project-1/searchTestClasses.py",
"chars": 32198,
"preview": "# searchTestClasses.py\n# --------------------\n# Licensing Information: You are free to use or extend these projects for"
},
{
"path": "Project-1/testClasses.py",
"chars": 6045,
"preview": "# testClasses.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# education"
},
{
"path": "Project-1/testParser.py",
"chars": 2990,
"preview": "# testParser.py\n# -------------\n# Licensing Information: You are free to use or extend these projects for\n# educational"
},
{
"path": "Project-1/test_cases/CONFIG",
"chars": 33,
"preview": "order: \"q1 q2 q3 q4 q5 q6 q7 q8\"\n"
},
{
"path": "Project-1/test_cases/q1/CONFIG",
"chars": 46,
"preview": "max_points: \"3\"\nclass: \"PassAllTestsQuestion\"\n"
},
{
"path": "Project-1/test_cases/q1/graph_backtrack.solution",
"chars": 273,
"preview": "# This is the solution file for test_cases/q1/graph_backtrack.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q1/graph_backtrack.test",
"chars": 778,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"depthFirstSearch\"\n\ndiagram: \"\"\"\n B \n ^\n |\n*A --> C --> G\n |\n V\n D\n\nA is the start"
},
{
"path": "Project-1/test_cases/q1/graph_bfs_vs_dfs.solution",
"chars": 279,
"preview": "# This is the solution file for test_cases/q1/graph_bfs_vs_dfs.test.\n# This solution is designed to support both right-t"
},
{
"path": "Project-1/test_cases/q1/graph_bfs_vs_dfs.test",
"chars": 675,
"preview": "# Graph where BFS finds the optimal solution but DFS does not\nclass: \"GraphSearchTest\"\nalgorithm: \"depthFirstSearch\"\n\ndi"
},
{
"path": "Project-1/test_cases/q1/graph_infinite.solution",
"chars": 286,
"preview": "# This is the solution file for test_cases/q1/graph_infinite.test.\n# This solution is designed to support both right-to-"
},
{
"path": "Project-1/test_cases/q1/graph_infinite.test",
"chars": 684,
"preview": "# Graph where natural action choice leads to an infinite loop\nclass: \"GraphSearchTest\"\nalgorithm: \"depthFirstSearch\"\n\ndi"
},
{
"path": "Project-1/test_cases/q1/graph_manypaths.solution",
"chars": 353,
"preview": "# This is the solution file for test_cases/q1/graph_manypaths.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q1/graph_manypaths.test",
"chars": 980,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"depthFirstSearch\"\n\ndiagram: \"\"\"\n B1 E1\n ^ \\ ^ \\\n / V "
},
{
"path": "Project-1/test_cases/q1/pacman_1.solution",
"chars": 2338,
"preview": "# This is the solution file for test_cases/q1/pacman_1.test.\n# This solution is designed to support both right-to-left\n#"
},
{
"path": "Project-1/test_cases/q1/pacman_1.test",
"chars": 856,
"preview": "# This is a basic depth first search test\nclass: \"PacmanSearchTest\"\nalgorithm: \"depthFirstSearch\"\n\n# The following speci"
},
{
"path": "Project-1/test_cases/q2/CONFIG",
"chars": 46,
"preview": "max_points: \"3\"\nclass: \"PassAllTestsQuestion\"\n"
},
{
"path": "Project-1/test_cases/q2/graph_backtrack.solution",
"chars": 277,
"preview": "# This is the solution file for test_cases/q2/graph_backtrack.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q2/graph_backtrack.test",
"chars": 780,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"breadthFirstSearch\"\n\ndiagram: \"\"\"\n B \n ^\n |\n*A --> C --> G\n |\n V\n D\n\nA is the sta"
},
{
"path": "Project-1/test_cases/q2/graph_bfs_vs_dfs.solution",
"chars": 256,
"preview": "# This is the solution file for test_cases/q2/graph_bfs_vs_dfs.test.\n# This solution is designed to support both right-t"
},
{
"path": "Project-1/test_cases/q2/graph_bfs_vs_dfs.test",
"chars": 677,
"preview": "# Graph where BFS finds the optimal solution but DFS does not\nclass: \"GraphSearchTest\"\nalgorithm: \"breadthFirstSearch\"\n\n"
},
{
"path": "Project-1/test_cases/q2/graph_infinite.solution",
"chars": 286,
"preview": "# This is the solution file for test_cases/q2/graph_infinite.test.\n# This solution is designed to support both right-to-"
},
{
"path": "Project-1/test_cases/q2/graph_infinite.test",
"chars": 686,
"preview": "# Graph where natural action choice leads to an infinite loop\nclass: \"GraphSearchTest\"\nalgorithm: \"breadthFirstSearch\"\n\n"
},
{
"path": "Project-1/test_cases/q2/graph_manypaths.solution",
"chars": 329,
"preview": "# This is the solution file for test_cases/q2/graph_manypaths.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q2/graph_manypaths.test",
"chars": 982,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"breadthFirstSearch\"\n\ndiagram: \"\"\"\n B1 E1\n ^ \\ ^ \\\n / V "
},
{
"path": "Project-1/test_cases/q2/pacman_1.solution",
"chars": 1036,
"preview": "# This is the solution file for test_cases/q2/pacman_1.test.\n# This solution is designed to support both right-to-left\n#"
},
{
"path": "Project-1/test_cases/q2/pacman_1.test",
"chars": 860,
"preview": "# This is a basic breadth first search test\nclass: \"PacmanSearchTest\"\nalgorithm: \"breadthFirstSearch\"\n\n# The following s"
},
{
"path": "Project-1/test_cases/q3/CONFIG",
"chars": 46,
"preview": "class: \"PassAllTestsQuestion\"\nmax_points: \"3\"\n"
},
{
"path": "Project-1/test_cases/q3/graph_backtrack.solution",
"chars": 277,
"preview": "# This is the solution file for test_cases/q3/graph_backtrack.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q3/graph_backtrack.test",
"chars": 779,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"uniformCostSearch\"\n\ndiagram: \"\"\"\n B \n ^\n |\n*A --> C --> G\n |\n V\n D\n\nA is the star"
},
{
"path": "Project-1/test_cases/q3/graph_bfs_vs_dfs.solution",
"chars": 256,
"preview": "# This is the solution file for test_cases/q3/graph_bfs_vs_dfs.test.\n# This solution is designed to support both right-t"
},
{
"path": "Project-1/test_cases/q3/graph_bfs_vs_dfs.test",
"chars": 676,
"preview": "# Graph where BFS finds the optimal solution but DFS does not\nclass: \"GraphSearchTest\"\nalgorithm: \"uniformCostSearch\"\n\nd"
},
{
"path": "Project-1/test_cases/q3/graph_infinite.solution",
"chars": 286,
"preview": "# This is the solution file for test_cases/q3/graph_infinite.test.\n# This solution is designed to support both right-to-"
},
{
"path": "Project-1/test_cases/q3/graph_infinite.test",
"chars": 685,
"preview": "# Graph where natural action choice leads to an infinite loop\nclass: \"GraphSearchTest\"\nalgorithm: \"uniformCostSearch\"\n\nd"
},
{
"path": "Project-1/test_cases/q3/graph_manypaths.solution",
"chars": 329,
"preview": "# This is the solution file for test_cases/q3/graph_manypaths.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q3/graph_manypaths.test",
"chars": 981,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"uniformCostSearch\"\n\ndiagram: \"\"\"\n B1 E1\n ^ \\ ^ \\\n / V "
},
{
"path": "Project-1/test_cases/q3/ucs_0_graph.solution",
"chars": 281,
"preview": "# This is the solution file for test_cases/q3/ucs_0_graph.test.\n# This solution is designed to support both right-to-lef"
},
{
"path": "Project-1/test_cases/q3/ucs_0_graph.test",
"chars": 848,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"uniformCostSearch\"\n\ndiagram: \"\"\"\n C\n ^\n | 2\n 2 V "
},
{
"path": "Project-1/test_cases/q3/ucs_1_problemC.solution",
"chars": 1042,
"preview": "# This is the solution file for test_cases/q3/ucs_1_problemC.test.\n# This solution is designed to support both right-to-"
},
{
"path": "Project-1/test_cases/q3/ucs_1_problemC.test",
"chars": 873,
"preview": "class: \"PacmanSearchTest\"\nalgorithm: \"uniformCostSearch\"\npoints: \"0.5\"\n\n# The following specifies the layout to be used "
},
{
"path": "Project-1/test_cases/q3/ucs_2_problemE.solution",
"chars": 1102,
"preview": "# This is the solution file for test_cases/q3/ucs_2_problemE.test.\n# This solution is designed to support both right-to-"
},
{
"path": "Project-1/test_cases/q3/ucs_2_problemE.test",
"chars": 883,
"preview": "class: \"PacmanSearchTest\"\nalgorithm: \"uniformCostSearch\"\npoints: \"0.5\"\n\n# The following specifies the layout to be used "
},
{
"path": "Project-1/test_cases/q3/ucs_3_problemW.solution",
"chars": 1950,
"preview": "# This is the solution file for test_cases/q3/ucs_3_problemW.test.\n# This solution is designed to support both right-to-"
},
{
"path": "Project-1/test_cases/q3/ucs_3_problemW.test",
"chars": 882,
"preview": "class: \"PacmanSearchTest\"\nalgorithm: \"uniformCostSearch\"\npoints: \"0.5\"\n\n# The following specifies the layout to be used "
},
{
"path": "Project-1/test_cases/q3/ucs_4_testSearch.solution",
"chars": 402,
"preview": "# This is the solution file for test_cases/q3/ucs_4_testSearch.test.\n# This solution is designed to support both right-t"
},
{
"path": "Project-1/test_cases/q3/ucs_4_testSearch.test",
"chars": 251,
"preview": "class: \"PacmanSearchTest\"\nalgorithm: \"uniformCostSearch\"\npoints: \"0.5\"\n\n# The following specifies the layout to be used "
},
{
"path": "Project-1/test_cases/q3/ucs_5_goalAtDequeue.solution",
"chars": 291,
"preview": "# This is the solution file for test_cases/q3/ucs_5_goalAtDequeue.test.\n# This solution is designed to support both righ"
},
{
"path": "Project-1/test_cases/q3/ucs_5_goalAtDequeue.test",
"chars": 751,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"uniformCostSearch\"\n\ndiagram: \"\"\"\n 1 1 1\n*A ---> B ---> C ---> [G]\n | "
},
{
"path": "Project-1/test_cases/q4/CONFIG",
"chars": 45,
"preview": "class: \"PassAllTestsQuestion\"\nmax_points: \"3\""
},
{
"path": "Project-1/test_cases/q4/astar_0.solution",
"chars": 277,
"preview": "# This is the solution file for test_cases/q4/astar_0.test.\n# This solution is designed to support both right-to-left\n# "
},
{
"path": "Project-1/test_cases/q4/astar_0.test",
"chars": 841,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"aStarSearch\"\n\ndiagram: \"\"\"\n C\n ^\n | 2\n 2 V 4 \n*"
},
{
"path": "Project-1/test_cases/q4/astar_1_graph_heuristic.solution",
"chars": 269,
"preview": "# This is the solution file for test_cases/q4/astar_1_graph_heuristic.test.\n# This solution is designed to support both "
},
{
"path": "Project-1/test_cases/q4/astar_1_graph_heuristic.test",
"chars": 964,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"aStarSearch\"\n\ndiagram: \"\"\"\n 2 3 2\n S --- A --- C ---> G\n | \\ / "
},
{
"path": "Project-1/test_cases/q4/astar_2_manhattan.solution",
"chars": 1045,
"preview": "# This is the solution file for test_cases/q4/astar_2_manhattan.test.\n# This solution is designed to support both right-"
},
{
"path": "Project-1/test_cases/q4/astar_2_manhattan.test",
"chars": 860,
"preview": "class: \"PacmanSearchTest\"\nalgorithm: \"aStarSearch\"\n\n# The following specifies the layout to be used \nlayoutName: \"medium"
},
{
"path": "Project-1/test_cases/q4/astar_3_goalAtDequeue.solution",
"chars": 293,
"preview": "# This is the solution file for test_cases/q4/astar_3_goalAtDequeue.test.\n# This solution is designed to support both ri"
},
{
"path": "Project-1/test_cases/q4/astar_3_goalAtDequeue.test",
"chars": 745,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"aStarSearch\"\n\ndiagram: \"\"\"\n 1 1 1\n*A ---> B ---> C ---> [G]\n | "
},
{
"path": "Project-1/test_cases/q4/graph_backtrack.solution",
"chars": 277,
"preview": "# This is the solution file for test_cases/q4/graph_backtrack.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q4/graph_backtrack.test",
"chars": 773,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"aStarSearch\"\n\ndiagram: \"\"\"\n B \n ^\n |\n*A --> C --> G\n |\n V\n D\n\nA is the start stat"
},
{
"path": "Project-1/test_cases/q4/graph_manypaths.solution",
"chars": 329,
"preview": "# This is the solution file for test_cases/q4/graph_manypaths.test.\n# This solution is designed to support both right-to"
},
{
"path": "Project-1/test_cases/q4/graph_manypaths.test",
"chars": 975,
"preview": "class: \"GraphSearchTest\"\nalgorithm: \"aStarSearch\"\n\ndiagram: \"\"\"\n B1 E1\n ^ \\ ^ \\\n / V / "
},
{
"path": "Project-1/test_cases/q5/CONFIG",
"chars": 59,
"preview": "class: \"PassAllTestsQuestion\"\nmax_points: \"3\"\ndepends: \"q2\""
},
{
"path": "Project-1/test_cases/q5/corner_tiny_corner.solution",
"chars": 93,
"preview": "# This is the solution file for test_cases/q5/corner_tiny_corner.test.\nsolution_length: \"28\"\n"
},
{
"path": "Project-1/test_cases/q5/corner_tiny_corner.test",
"chars": 142,
"preview": "class: \"CornerProblemTest\"\n\nlayoutName: \"tinyCorner\"\nlayout: \"\"\"\n%%%%%%%%\n%. .%\n% P %\n% %%%% %\n% % %\n% % %%%%\n%"
},
{
"path": "Project-1/test_cases/q6/CONFIG",
"chars": 62,
"preview": "class: \"Q6PartialCreditQuestion\"\nmax_points: \"3\"\ndepends: \"q4\""
},
{
"path": "Project-1/test_cases/q6/corner_sanity_1.solution",
"chars": 238,
"preview": "# In order for a heuristic to be admissible, the value\n# of the heuristic must be less at each state than the\n# true cos"
},
{
"path": "Project-1/test_cases/q6/corner_sanity_1.test",
"chars": 145,
"preview": "class: \"CornerHeuristicSanity\"\npoints: \"1\"\n\n# The following specifies the layout to be used \nlayout: \"\"\"\n%%%%%%\n%. .%\n%"
},
{
"path": "Project-1/test_cases/q6/corner_sanity_2.solution",
"chars": 237,
"preview": "# In order for a heuristic to be admissible, the value\n# of the heuristic must be less at each state than the\n# true cos"
},
{
"path": "Project-1/test_cases/q6/corner_sanity_2.test",
"chars": 145,
"preview": "class: \"CornerHeuristicSanity\"\npoints: \"1\"\n\n# The following specifies the layout to be used \nlayout: \"\"\"\n%%%%%%\n%. .%\n%"
},
{
"path": "Project-1/test_cases/q6/corner_sanity_3.solution",
"chars": 348,
"preview": "# In order for a heuristic to be admissible, the value\n# of the heuristic must be less at each state than the\n# true cos"
},
{
"path": "Project-1/test_cases/q6/corner_sanity_3.test",
"chars": 182,
"preview": "class: \"CornerHeuristicSanity\"\npoints: \"1\"\n\n# The following specifies the layout to be used \nlayout: \"\"\"\n%%%%%%%%\n%.% "
},
{
"path": "Project-1/test_cases/q6/medium_corners.solution",
"chars": 783,
"preview": "# This solution file specifies the length of the optimal path\n# as well as the thresholds on number of nodes expanded to"
},
{
"path": "Project-1/test_cases/q6/medium_corners.test",
"chars": 531,
"preview": "class: \"CornerHeuristicPacman\"\n\n# The following specifies the layout to be used \nlayout: \"\"\"\n%%%%%%%%%%%%%%%%%%%%%%%%%%%"
},
{
"path": "Project-1/test_cases/q7/CONFIG",
"chars": 60,
"preview": "class: \"PartialCreditQuestion\"\nmax_points: \"4\"\ndepends: \"q4\""
},
{
"path": "Project-1/test_cases/q7/food_heuristic_1.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_1.test.\nsolution_cost: \"0\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_1.test",
"chars": 164,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 1\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_10.solution",
"chars": 89,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_10.test.\nsolution_cost: \"7\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_10.test",
"chars": 175,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 10\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_11.solution",
"chars": 89,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_11.test.\nsolution_cost: \"8\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_11.test",
"chars": 175,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 11\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_12.solution",
"chars": 89,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_12.test.\nsolution_cost: \"1\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_12.test",
"chars": 175,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 12\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_13.solution",
"chars": 89,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_13.test.\nsolution_cost: \"5\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_13.test",
"chars": 175,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 13\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_14.solution",
"chars": 90,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_14.test.\nsolution_cost: \"31\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_14.test",
"chars": 251,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 14\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_15.solution",
"chars": 90,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_15.test.\nsolution_cost: \"21\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_15.test",
"chars": 226,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 15\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_16.solution",
"chars": 89,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_16.test.\nsolution_cost: \"7\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_16.test",
"chars": 165,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 16\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_17.solution",
"chars": 90,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_17.test.\nsolution_cost: \"16\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_17.test",
"chars": 184,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 17\"\nlayout:"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_2.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_2.test.\nsolution_cost: \"0\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_2.test",
"chars": 225,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 2\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_3.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_3.test.\nsolution_cost: \"0\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_3.test",
"chars": 164,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 3\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_4.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_4.test.\nsolution_cost: \"0\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_4.test",
"chars": 183,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 4\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_5.solution",
"chars": 89,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_5.test.\nsolution_cost: \"11\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_5.test",
"chars": 164,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 5\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_6.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_6.test.\nsolution_cost: \"5\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_6.test",
"chars": 164,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 6\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_7.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_7.test.\nsolution_cost: \"7\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_7.test",
"chars": 169,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 7\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_8.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_8.test.\nsolution_cost: \"5\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_8.test",
"chars": 164,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 8\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_9.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_9.test.\nsolution_cost: \"6\"\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_9.test",
"chars": 164,
"preview": "class: \"HeuristicTest\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"Test 9\"\nlayout: "
},
{
"path": "Project-1/test_cases/q7/food_heuristic_grade_tricky.solution",
"chars": 108,
"preview": "# This is the solution file for test_cases/q7/food_heuristic_grade_tricky.test.\n# File intentionally blank.\n"
},
{
"path": "Project-1/test_cases/q7/food_heuristic_grade_tricky.test",
"chars": 406,
"preview": "class: \"HeuristicGrade\"\n\nheuristic: \"foodHeuristic\"\nsearchProblemClass: \"FoodSearchProblem\"\nlayoutName: \"trickySearch\"\nl"
},
{
"path": "Project-1/test_cases/q8/CONFIG",
"chars": 45,
"preview": "class: \"PassAllTestsQuestion\"\nmax_points: \"3\""
},
{
"path": "Project-1/test_cases/q8/closest_dot_1.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_1.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_1.test",
"chars": 98,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 1\"\nlayout: \"\"\"\n%%%%%%\n%....%\n%....%\n%P...%\n%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_10.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q8/closest_dot_10.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_10.test",
"chars": 185,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 10\"\nlayout: \"\"\"\n%%%%%%%%%%\n% %\n% ...%...%\n% .%.%.%.%\n% .%.%.%.%\n% .%.%"
},
{
"path": "Project-1/test_cases/q8/closest_dot_11.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q8/closest_dot_11.test.\nsolution_length: \"2\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_11.test",
"chars": 160,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 11\"\nlayout: \"\"\"\n%%%\n% %\n% %\n% %\n% %\n% %\n%.%\n%.%\n% %\n% %\n% %\n% %\n% %\n% %\n% %\n%"
},
{
"path": "Project-1/test_cases/q8/closest_dot_12.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q8/closest_dot_12.test.\nsolution_length: \"3\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_12.test",
"chars": 99,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 12\"\nlayout: \"\"\"\n%%%%\n% .%\n% %\n%P %\n% %\n% .%\n%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_13.solution",
"chars": 88,
"preview": "# This is the solution file for test_cases/q8/closest_dot_13.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_13.test",
"chars": 118,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 13\"\nlayout: \"\"\"\n%%%%%%%%\n%.%....%\n%.% %%.%\n%.%P%%.%\n%... .%\n%%%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_2.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_2.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_2.test",
"chars": 98,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 2\"\nlayout: \"\"\"\n%%%%%%\n% .%\n%.P..%\n% %\n%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_3.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_3.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_3.test",
"chars": 103,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 3\"\nlayout: \"\"\"\n%%%%%%%\n% .%\n%. P..%\n% %\n%%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_4.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_4.test.\nsolution_length: \"3\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_4.test",
"chars": 98,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 4\"\nlayout: \"\"\"\n%%%%%%\n% .%\n% .%\n%P .%\n%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_5.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_5.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_5.test",
"chars": 98,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 5\"\nlayout: \"\"\"\n%%%%%%\n% %. %\n% %%.%\n%P. .%\n%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_6.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_6.test.\nsolution_length: \"2\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_6.test",
"chars": 108,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 6\"\nlayout: \"\"\"\n%%%%%%%%\n% %\n%. P .%\n% %\n%%%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_7.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_7.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_7.test",
"chars": 108,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 7\"\nlayout: \"\"\"\n%%%%%%%%\n% %\n% P %\n%. . .%\n%%%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_8.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_8.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_8.test",
"chars": 108,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 8\"\nlayout: \"\"\"\n%%%%%%%%\n% %\n% P.%\n% %\n%%%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_9.solution",
"chars": 87,
"preview": "# This is the solution file for test_cases/q8/closest_dot_9.test.\nsolution_length: \"1\"\n"
},
{
"path": "Project-1/test_cases/q8/closest_dot_9.test",
"chars": 108,
"preview": "class: \"ClosestDotTest\"\n\nlayoutName: \"Test 9\"\nlayout: \"\"\"\n%%%%%%%%\n% %\n%P. .%\n% %\n%%%%%%%%\n\"\"\"\n\n"
},
{
"path": "Project-1/textDisplay.py",
"chars": 2298,
"preview": "# textDisplay.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# education"
},
{
"path": "Project-1/util.py",
"chars": 25735,
"preview": "# util.py\n# -------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes pr"
},
{
"path": "Project-2/VERSION",
"chars": 8,
"preview": "v1.002\r\n"
},
{
"path": "Project-2/autograder.py",
"chars": 14027,
"preview": "# autograder.py\n# -------------\n# Licensing Information: You are free to use or extend these projects for\n# educational"
},
{
"path": "Project-2/game.py",
"chars": 25518,
"preview": "# game.py\n# -------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes pr"
},
{
"path": "Project-2/ghostAgents.py",
"chars": 3108,
"preview": "# ghostAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# education"
},
{
"path": "Project-2/grading.py",
"chars": 9271,
"preview": "# grading.py\n# ----------\n# Licensing Information: You are free to use or extend these projects for\n# educational purpo"
},
{
"path": "Project-2/graphicsDisplay.py",
"chars": 28031,
"preview": "# graphicsDisplay.py\n# ------------------\n# Licensing Information: You are free to use or extend these projects for\n# e"
},
{
"path": "Project-2/graphicsUtils.py",
"chars": 11785,
"preview": "# graphicsUtils.py\n# ----------------\n# Licensing Information: You are free to use or extend these projects for\n# educa"
},
{
"path": "Project-2/keyboardAgents.py",
"chars": 3045,
"preview": "# keyboardAgents.py\n# -----------------\n# Licensing Information: You are free to use or extend these projects for\n# edu"
},
{
"path": "Project-2/layout.py",
"chars": 5753,
"preview": "# layout.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purpose"
},
{
"path": "Project-2/layouts/capsuleClassic.lay",
"chars": 141,
"preview": "%%%%%%%%%%%%%%%%%%%\n%G. G ....%\n%.% % %%%%%% %.%%.%\n%.%o% % o% %.o%.%\n%.%%%.% %%% %..%.%\n%..... P %..%G%\n"
}
]
// ... and 471 more files (download for full content)
About this extraction
This page contains the full source code of the molson194/Artificial-Intelligence-Berkeley-CS188 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 671 files (59.2 MB), approximately 9.8M tokens, and a symbol index with 2632 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.