Week 9 Implementing commands - PowerPoint PPT Presentation

1 / 58
About This Presentation
Title:

Week 9 Implementing commands

Description:

Players specify the direction in which they wish their party to move. If an available exit exists in the direction specified ... An alien spaceship ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 59
Provided by: gregorys151
Category:

less

Transcript and Presenter's Notes

Title: Week 9 Implementing commands


1
Week 9 Implementing commands
2
Assignment 1
  • Expecting to hand it back week 10

3
SET/SEU
  • Next week

4
Today
  • Some more commands
  • Introduction to design patterns

5
The move command revisited
  • The base code for the assignment has two commands
    already written
  • go
  • quit
  • Last week we wrote a user story for the move
    command

6
Player Move Story
  • Players specify the direction in which they wish
    their party to move.
  • If an available exit exists in the direction
    specified
  • the system updates the players party location,
  • returns a description of the new location
  • the players turn ends.

7
Question
  • What do we need to implement in order to code
    this user story
  • Remembering that it is our first command

8
Executing a command
  • Whats involved?

9
A single command
  • Tell the system
  • System must receive the message
  • System must interpret the message correctly
  • System must perform actions required by the
    command

10
Completing a turn
  • A player completes their turn after they
    successfully execute a command such as move,
    attack, buy, sell, get, drop (something which
    takes time)
  • A player does not complete their turn by looking
    at something, if they enter an invalid command or
    they are unsuccessful at moving location (ie
    something where the time is negligible)

11
Two things
  • Parsing the input
  • Implementing the command itself

12
Parse Player Input Story
  • Commands will have the format
  • action argument(s).
  • Only one command can be invoked at a time.
  • For example go south would indicate the user
    wishes to invoke the go command with the argument
    south.

13
  • A simple (looking) command like
  • Go east
  • is really quite complex
  • Whats involved?
  • What classes might we need?

14
  • We need to get the string containing the action
  • The string needs to be tokenised (broken up into
    individual strings)
  • The string needs to be analysed for meaning
    (parsed)
  • The action based on this meaning needs to be
    performed (executed)

15
Control Classes
  • Parser
  • Responsible for translating the input from the
    user interface into a UserInput object
  • ParsedInput
  • Encapsulates user input broken down into separate
    action and arguments components

16
First attempt at implementing the command
  • public String ProcessTurn(IMazeClient theClient,
    PlayerCharacter thePlayer)
  • ParsedInput validInput
    theParser.Parse(theClient.GetCommand())
  • // use command pattern here instead of
    nested logic
  • if (validInput .Command "go")
  • return moveParty(validInput,
    theClient)
  • else if (validInput .Command quit")
  • return quitGame(validInput,
    theClient)
  • return Cant find that command

17
Problems
  • Inflexible
  • Existing classes need to be changed each time we
    need to add a new command

18
After Command Pattern
  • public CommandHandler()
  • commandList new Hashtable()
  • commandList.put("go", new GoCommand())
  • commandList.put("get", new GetCommand())
  • commandList.put("drop", new
    DropCommand())
  • commandList.put("unlock", new
    UnlockCommand())
  • commandList.put("inv", new
    InventoryCommand())
  • public String handleCommand(StringTokenizer
    input, DungeonMaster dm)
  • String cmdVerb input.nextToken()
  • // use command pattern here instead of
    nested logic
  • Command command (Command)
    commandList.get(cmdVerb)
  • if (!command null)
  • return command.execute(input, dm)
  • return Cant find that command

19
Benefits/Drawbacks
  • Benefits
  • Command decouples the object that invokes the
    operation from the one that knows how to perform
    it.
  • Commands are first-class objects. They can be
    manipulated and extended like any other object.
  • It's easy to add new Commands, because you don't
    have to change existing classes.
  • Drawbacks
  • For a small number of functions the increased
    complexity might not be justified

20
(No Transcript)
21
Command Pattern UML
22
Design Patterns
  • Actually, its a situation that programmers have
    faced many times.
  • The Gang of Four have taken this situation (and
    22 others) and described design patterns.
  • Well digress for a little while now to discuss
    design patterns in general

23
Consider . . .
  • An alien spaceship
  • If it crashed on Earth would it automatically
    mean that we suddenly advance millions of years
    in our technology?

24
How would you
  • Organise a trip to Ulan Bator?

25
Point is . . .
  • We will normally solve problems by using
    solutions that have already worked for us.
  • You (and I) have already done this many times in
    our own software development.
  • What is the problem with this?

26
Design Patterns
  • Many of our solutions are not appropriate.
  • It would be useful to have a set of solutions
    that have already been proven to work.
  • Gamma et al (So-called Gang of Four) produced a
    famous book which listed 23 Design patterns
  • A must if you want to continue with your
    programming

27
Design Patterns
  • Each pattern describes a problem which occurs
    over and over again in our environment, and then
    describes the core of the solution to that
    problem, in such a way that you can use this
    solution a million times over, without ever doing
    it the same way twice. Christopher Alexander
  • What was Christopher Alexander?

28
An Architect!!!
  • Current use comes from the work of the architect
    Christopher Alexander
  • Alexander studied ways to improve the process of
    designing buildings and urban areas
  • Patterns can be applied to many different areas
    of human endeavour, including software
    development

29
A Design Pattern is
  • SMART - an elegant solution not obvious to a
    novice
  • GENERIC - not dependent upon a system,
    programming language or application domain
  • WELL-PROVEN - has been identified from real OO
    systems
  • SIMPLE - is usually quite small, involving only a
    handful of classes
  • REUSABLE - is documented in such a fashion that
    it is easy to reuse
  • OBJECT-ORIENTED - built with OO mechanisms such
    as classes, objects, generalization and
    polymorphism

30
A Design Pattern has
  • Pattern Name - a handle we can use to describe a
    design problem, its solutions and consequences
  • Problem - describes when to apply the pattern. It
    explains the problem and its context
  • Solution - describes the elements which make up
    the solution and their relationships
  • Consequences - the results and trade-offs of
    using the design pattern

31
Gang Of Four
  • Design Patterns communicate solutions to common
    programming problems
  • The seminal book on design patterns Design
    Patterns, Elements of Reusable Object-Oriented
    Software by Gamma et al, (1995)

32
Design Patterns
  • 23 design patterns identified
  • Grouped into three categories
  • Creational concerned with how objects
    are created
  • Structural concerned with how object fit
    together
  • Behavioural concerned with the
    functionality of objects

33
Overriding principle
  • Program to an interface not an implementation
  • What example of this is apparent in the code for
    assignment 2?

34
Advantages
  • Clients remain unaware of the specific types of
    objects they use
  • They just need to conform to the interface
  • Client remain unaware of the classes that
    implement these objects
  • They just know about the abstract classes
    defining the interface

35
Working together
  • Often design patterns work together to form
    solutions
  • Well see examples of this as we work through

36
Inheritance vs Composition
  • Inheritance
  • Benefits
  • Easy to use
  • built into programming language
  • Easier to modify the implementation
  • Use subclassing
  • Drawbacks
  • Cant change implementations at run time
  • Inheritance is defined at compile-time
  • Inheritance breaks encapsulation how?

37
Inheritance vs Composition
  • Composition
  • Objects acquire references to other objects
  • Benefits
  • Encapsulation is not broken
  • Why not?
  • An object can be replaced at run-time with an
    object
  • Must have the same interface

38
Command
  • Context/Problem
  • Sometimes it's necessary to issue requests to
    objects without knowing anything about the
    operation being requested or the receiver of the
    request.
  • Solution
  • Encapsulate a request as an object, thereby
    letting you parameterize clients with different
    requests, queue or log requests, and support
    undoable operations.

39
Command Pattern UML
40
Question
  • What classes correspond to the conceptual classes
    in the previous slide?

41
  • Invoker
  • Creator
  • Command
  • ConcreteCommand

42
  • Invoker CommandHandler
  • Creator CommandHandler
  • Command Command
  • ConcreteCommand GetCommand
  • LookCommand
  • QuitCommand

43
Command Pattern (GOF)
  • The command pattern yields a more flexible and
    extensible design for handling user input
  • In our case it cuts out all the embedded
    if-then-else statements!
  • Basically we have a single abstract superclass
    Command which defines an abstract method
    execute()
  • We then create a series of concrete subclasses
    which each are responsible for performing a
    single command

44
After Command Pattern
  • private void SetupCommands()
  • availableCommands.Add("go", new
    GoCommand())
  • availableCommands.Add("quit", new
    QuitCommand())
  • availableCommands.Add("look", new
    LookCommand())
  • public CommandResponse ProcessTurn(IMazeClie
    nt theClient, PlayerCharacter thePlayer)
  • ParsedInput validInput
    theParser.Parse(theClient.GetCommand())
  • Command theCommand availableCommandsvalidInpu
    t.Command
  • return theCommand.Execute(validInpu
    t, thePlayer)

45
Control Classes
  • CommandResponse
  • Encapsulates the results of executing a command
  • CommandHandler
  • Responsible for delegating control to the correct
    Command class
  • Command
  • Abstract class which all game commands inherit
    from
  • GoCommand
  • Concrete class which handles a request for
    movement of a GameCharacter

46
User Story Look
  • Players specify they wish to look at an object.
  • The system responds with a description of the
    object
  • Objects may be
  • the players location,
  • an item at the players location,
  • an item being carried by the player
  • or another character co-located with the player.

47
Look Story Comments
  • We currently dont have NPCs or items so we cant
    look at them.
  • The only option we have at present is to
    implement the look command to return a
    description of the players current location.
  • Lets break down the user story to reflect this
    change.

48
User Story Look Location
  • Players specify they wish to look at the current
    location.
  • The system responds with a description of the
    location and any available exits.

49
Implementing NPC movement
50
User Story Move NPC
  • The system randomly moves each mobile NPC
    character after the player has completed their
    turn.

51
Questions
  • When are NPC objects created?
  • At load time -gt must be stored in the IMazeData
    object!

52
Questions
  • When do NPCs move?
  • After the player character completes their turn.
  • Some commands complete a players turn (move,
    buy, sell, attack, get item, drop item) others
    are instantaneous (look, change weapon, etc)
  • What class is responsible for moving the NPCs
  • Create a dedicated handler object NPCHandler.
  • The DungeonMaster class coordinates control
    between the CommandHandler and the NPCHandler

53
NPC
  • Non-player Character
  • NPCs have the attributes of characters plus
    additional attributes
  • Hostile to player (yes/no)
  • A description
  • Conversation ??
  • Implies a new class NonPlayerCharacter which
    inherits from GameCharacter
  • NonPlayerCharacter is a bit on the long side for
    a class name other choices could be NPC or
    VirtualCharacter
  • Well use the abbreviation NPC because it is well
    understood in the domain and has been defined in
    our glossary.

54
DungeonMaster
  • private void GameLoop()
  • while (true)
  • CommandResponse response
    commandProcessor.ProcessTurn(theClient.GetCommand(
    ), thePlayer)
  • theClient.GameMessage(response.Mes
    sage)
  • if (response.FinishedGame)
  • break
  • if (response.FinishedTurn)
  • // process NPC turn

55
Implementing Look NPC
56
Look NPC
  • Now that we have NPCs moving around in our
    virtual world we can extend the look command to
    handle the case when a player would like to look
    at an NPC which is currently in eyeshot (current
    location)

57
User Story Look NPC
  • Player specifies they wish to look at a
    particular NPC by specifying their name. The
    system responds with a description of the NPC.

58
Questions to ask
  • What do players see when looking at a NPC?
  • The player is returned a description of the NPC ?
    so add a description attribute to the class
  • Where do you put the logic for look at
    character?
  • In the look command!
Write a Comment
User Comments (0)
About PowerShow.com