-
Notifications
You must be signed in to change notification settings - Fork 0
/
sampleAgents.py
77 lines (69 loc) · 2.53 KB
/
sampleAgents.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# sampleAgents.py
# parsons/07-oct-2017
#
# Version 1.1
#
# Some simple agents to work with the PacMan AI projects from:
#
# http://ai.berkeley.edu/
#
# These use a simple API that allow us to control Pacman's interaction with
# the environment adding a layer on top of the AI Berkeley code.
#
# As required by the licensing agreement for the PacMan AI we have:
#
# 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
# ([email protected]) and Dan Klein ([email protected]).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel ([email protected]).
# The agents here are extensions written by Simon Parsons, based on the code in
# pacmanAgents.py
from pacman import Directions
from game import Agent
import api
import random
import game
import util
# RandomAgent
#
# A very simple agent. Just makes a random pick every time that it is
# asked for an action.
class RandomAgent(Agent):
def getAction(self, state):
# Get the actions we can try, and remove "STOP" if that is one of them.
legal = api.legalActions(state)
if Directions.STOP in legal:
legal.remove(Directions.STOP)
# Random choice between the legal options.
return api.makeMove(random.choice(legal), legal)
# RandomishAgent
#
# A tiny bit more sophisticated. Having picked a direction, keep going
# until that direction is no longer possible. Then make a random
# choice.
class RandomishAgent(Agent):
# Constructor
#
# Create a variable to hold the last action
def __init__(self):
self.last = Directions.STOP
def getAction(self, state):
# Get the actions we can try, and remove "STOP" if that is one of them.
legal = api.legalActions(state)
if Directions.STOP in legal:
legal.remove(Directions.STOP)
# If we can repeat the last action, do it. Otherwise make a
# random choice.
if self.last in legal:
return api.makeMove(self.last, legal)
else:
pick = random.choice(legal)
# Since we changed action, record what we did
self.last = pick
return api.makeMove(pick, legal)