Moving around a small grid: Difference between revisions

From Computer Science Wiki
(Created page with "right|frame|This a problem set for you to work through This is a problem set. Some of these are easy, others are far more difficult. The purpose of these...")
 
 
(26 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[File:square.png|right|frame|This a problem set for you to work through]]
[[File:square.png|right|frame|This a problem set for you to work through <ref>http://www.flaticon.com/</ref>]]


This is a problem set. Some of these are easy, others are far more difficult. The purpose of these problems sets are to HELP YOU THINK THROUGH problems. The solution is at the bottom of this page, but please don't look at it until you have tried (and failed) at least three or four times.  
This is a problem set. Some of these are easy, others are far more difficult. The purpose of these problems sets are to HELP YOU THINK THROUGH problems. The solution is at the bottom of this page, but please don't look at it until you have tried (and failed) at least three or four times.  
Line 5: Line 5:
== The Problem ==
== The Problem ==


This problem is designed to test your skill and knowledge of [[string]]s, specifically your knowledge and understanding of combining (concatenating) strings.  
This problem is designed to test your skill and knowledge of [[functions]], [[variables]] and [[computational thinking]].
    
    
: The web is built with HTML strings like "<syntaxhighlight lang="python" inline><i>Yay</i></syntaxhighlight>" which draws Yay as italic text. In this example, the "i" tag makes <i> and </i> which surround the word "Yay". Given tag and word strings, create the HTML string with tags around the word <ref>http://codingbat.com/prob/p132290</ref>
You have a simple 10 x 10 grid, with your character at the center (5,5). You can move up, down, left and right. Add:


== Some Code to Get You Started ==
* terrain (add water, add hills, add town, add logical terrain (trees should be like a forest, water like a lake)).
* a bad guy
* combat
* basic AI
* basic statistics for the bad guy (or you) like Hit Points, Armour, Power, etc...


<syntaxhighlight lang="python" line="1" >
== The basic game ==
 
<syntaxhighlight lang="python" >
import random
import prettytable
import colorama
from colorama import Fore, Back, Style
 
grid = []
 
# let's make our map. We are making a  25 x 25 map
# for our terrain, we are going to randomly insert a number from 1 to 4
#
#
# this is the start of a simple game on a 10 x 10 grid that let's players move around in a fairly simple way.
# 1 is normal ground ...
#
# 2 is normal ground ...
# currently, all we have is movement and updating the board. But if a student wanted to add TERRAIN, BAD GUYS, COMBAT, and maybe even BASIC AI
# 3 is a tree .*.
# that would be pretty cool, huh?
# 4 is a mountain .^.
# 5 is the player [T]
 
for i in range(0,625):
    grid.append(random.randrange(1,5))
 
# now we can manually change our terrain. This code puts a basic mountain range
# at the very top of our map.
 
grid.insert(0,4)
grid.insert(1,4)
grid.insert(2,4)
grid.insert(3,4)
grid.insert(4,4)
grid.insert(5,4) 
 
   
# now we place the player
   
grid.insert(317,5)
 
# and let's keep track of where the player is.  
 
current_player_location = 317
 
 
# remember we have a 25 x 25 grid, which we are representing in a simple list.
# this means row 1 is 0 to 24, row 2 is 25 to 49, row 3 is 50 to 74, etc...
# You should remember this when you work on the move code.
#  


current_player_y_position = 3
def draw_board():
current_player_x_position = 5
    row = 0
      
     for i in range(0,625):
def move(direction,pos_y,pos_x):
        if grid[i] == 1:
    if direction == "up":
            print(Style.DIM + Fore.YELLOW + "..." + Style.RESET_ALL ,end='')
         if pos_y == 1:
         elif grid[i] == 2:
             print("-----------------------")
             print(Style.DIM + Fore.YELLOW + "..." + Style.RESET_ALL ,end='')
             print("You cannot go that way.")
        elif grid[i] == 3:
             print("-----------------------")
             print("." + Fore.GREEN + "*" + Style.RESET_ALL + ".",end='')
             foo = raw_input("Press enter to continue...")
        elif grid[i] == 4:
             print("." + Style.DIM + Fore.WHITE + "^" + Style.RESET_ALL + ".",end='')
        elif grid[i] == 5:
             print("[" + Style.BRIGHT + Fore.RED + "T" + Style.RESET_ALL + "]",end='')
         else:
         else:
             print("-----------------------")
             print("ERR"),
             print("You walk up one square. ")
        row = row + 1
             print("-----------------------")
        if row == 25:
            global current_player_x_position
             print ("\n")
            global current_player_y_position
             row = 0
            current_player_y_position = current_player_y_position - 1
    return
            foo = raw_input("Press enter to continue...")
 
     elif direction == "right":
def move(where_do_you_want_go):
         if pos_x == 10:
    global current_player_location
            print("-----------------------")
    current_player_position = grid.index(5)
             print("You cannot go that way.")
     if where_do_you_want_go == "up":
            print("-----------------------")
        #
             foo = raw_input("Press enter to continue...")
        # let's make sure we are not at the top row, which is 0 to 24
        #
         if grid.index(5) <=25:
             print("You can't go up anymore.")
        elif grid[current_player_position - 25] == 3 or grid[current_player_position - 25] == 4:
             print("You cannot go up, as there is an obstacle in your path!")
         else:
         else:
             print("---------------------------")
             print("The player is at position " +  str(grid.index(5)))
        print("You walk right one square. ")
             grid[current_player_position - 25] = 5
             print("---------------------------")
             grid[current_player_position] = 1
            global current_player_x_position
             print("The new player is at position " +  str(grid.index(5)))
            global current_player_y_position
               
             current_player_x_position = current_player_x_position +1
     elif where_do_you_want_go == "down":
             foo = raw_input("Press enter to continue...")  
         current_player_position = grid.index(5)
     elif direction == "left":
        #
         if pos_x == 1:
        # let's make sure we are not at the bottom row, which is 600 to 624
            print("-----------------------")
        #
             print("You cannot go that way.")
        if grid.index(5) >=600:
             print("-----------------------")
             print("You can't go down anymore.")
            foo = raw_input("Press enter to continue...")
        elif grid[current_player_position + 25] == 3 or grid[current_player_position + 25] == 4:
             print("You cannot move down, as there is an obstacle in your path!")  
         else:
         else:
             print("---------------------------")
             print("The player is at position " +  str(grid.index(5)))
        print("You walk left one square. ")
             grid[current_player_position + 25] = 5
            print("---------------------------")
             grid[current_player_position] = 1
             global current_player_x_position
             print("The new player is at position " +  str(grid.index(5)))
            global current_player_y_position
     
             current_player_x_position = current_player_x_position -1
     elif where_do_you_want_go == "right":
             foo = raw_input("Press enter to continue...")
        current_player_position = grid.index(5)
     elif direction == "down":
        #
         if pos_y == 10:
        # let's make sure we are not at the bottom row, which is 600 to 624
            print("-----------------------")
        #
             print("You cannot go that way.")
         if grid.index(5) % 25 == 24:
             print("-----------------------")
             print("You can't go right anymore.")
            foo = raw_input("Press enter to continue...")
        elif grid[current_player_position + 1] == 3 or grid[current_player_position + 1] == 4:
             print("You cannot move right, as there is an obstacle in your path!")    
         else:
         else:
             print("-----------------------")
             print("The player is at position " +  str(grid.index(5)))
             print("You walk down one square. ")
             grid.insert(current_player_position + 1, grid.pop(current_player_position))
             print("-----------------------")
             print("The new player is at position " + str(grid.index(5)))  
            global current_player_x_position
     
            global current_player_y_position
     elif where_do_you_want_go == "left":
            current_player_y_position = current_player_y_position + 1
         current_player_position = grid.index(5)
            foo = raw_input("Press enter to continue...")            
        #
    return
        # let's make sure we are not at the bottom row, which is 600 to 624
   
        #
        if grid.index(5) % 25 == 0:
            print("You can't go left anymore.")
def update_board(x_position, y_position):
        elif grid[current_player_position - 1] == 3 or grid[current_player_position - 1] == 4:
     if x_position == current_player_x_position and y_position == current_player_y_position:
            print("You cannot move left, as there is an obstacle in your path!")    
        token = "T"
        else:
    else:
            print("The player is at position " +  str(grid.index(5)))
         token = "_"
            grid.insert(current_player_position - 1, grid.pop(current_player_position))  
    return token
             print("The new player is at position " + str(grid.index(5)))                          
    return
 
def draw_board():
def inventory():
    y_counter = 1
    inventory = {'axe':1, 'pick axe':1, 'food':10}
    x_counter = 1
    inventory_table = prettytable(['Item', 'Quantity'])
    counter_heading = 1
     inventory_table.align["Item"] = "l"
    print("\n")
     for i,e in inventory.iteritems():
    print(" " * 4),
        inventory_table.add_row([str(i), e])
    while counter_heading < 11:
     print(inventory_table)
        print(str(counter_heading).zfill(2) + "  "),
     foo = input("Press enter to contnue...")
        counter_heading = counter_heading + 1
    print("\n")
    while y_counter < 11:
        print(str(y_counter).zfill(2) + " |")
        while x_counter < 11:   
             print("_" + update_board(x_counter, y_counter) + "_ |"),   
            x_counter = x_counter + 1
        print("\n")
        y_counter = y_counter + 1
        x_counter = 1
def help():
     print("\n")
     print("Type 99 to quit. Type up, down, left, right to move around.")
     print("-----------------------------------------------------------")
     foo = raw_input("Press enter to continue...")  
     return
     return
     
 
 
def main():
def main():
    global current_player_y_position
    global current_player_x_position
     while True:
     while True:
         draw_board()
         draw_board()
         choice = raw_input("What do you want to do (type help for help) > ")
        print("Your current position is: " + str(grid.index(5)))
        print("Other information should appear here. ")
        print("Up, you see " + str(grid[grid.index(5)-25]))
        print("\n")
         choice = input("What do you want to do (type help for help) > ")
         if choice == "99":
         if choice == "99":
             break
             break
         elif choice == "help":
         elif choice == "help":
             help()
             help()
         elif choice == "up":
         elif choice == "u":
             move('up',current_player_y_position,current_player_x_position)
             move('up')
         elif choice == "right":
         elif choice == "r":
             move('right',current_player_y_position,current_player_x_position)
             move('right')
         elif choice == "left":
         elif choice == "l":
             move('left',current_player_y_position,current_player_x_position)  
             move('left')
         elif choice == "down":
         elif choice == "d":
             move('down',current_player_y_position,current_player_x_position)                      
             move('down')
        elif choice == "i":
            inventory()                         
     return
     return
 
main()
main()
</syntaxhighlight>
</syntaxhighlight>


== Take This Farther ==
== Take this farther ==
 
You want to go farther?
 
* add color to this
* add many types of different entities (google nethack)
* move the board to 50 x 50
* add an option to SAVE / RESTORE a game


This simple function is very useful, and it is likely that you have used a function like this to add bold face text to a google doc.  
Make a decent map.


* Please create a function that creates a link. <syntaxhighlight lang="python" inline><a href="http://reddit.com/r/python">Click here</a></syntaxhighlight>. You will need the link and text to display to the user.
* [https://www.google.pl/search?q=3d+text+grid&safe=strict&espv=2&biw=1280&bih=594&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi0svKLp9bLAhXLVSwKHfEJBOQQ_AUIBigB#safe=strict&tbm=isch&q=ascii+map+rpg&imgrc=_ click here to see a google image search result for ascii maps]
* Add some logic which rejects [http://www.w3schools.com/tags/ref_html_dtd.asp invalid HTML tags]


== How you will be assessed ==
== How you will be assessed ==
Line 153: Line 201:
== References ==
== References ==


* Icons made by [http://www.freepik.com Freepik] from [http://www.flaticon.com www.flaticon.com] is licensed by [http://creativecommons.org/licenses/by/3.0/ CC 3.0 BY]
 
<references />
<references />


== One Possible Solution ==
<div class="toccolours mw-collapsible mw-collapsed">
Click the expand link to see one possible solution, but NOT before you have tried and failed!
<div class="mw-collapsible-content">
<syntaxhighlight lang="python" line="1" >
#
# this function returns a HTML opening and closing pair of tag
#
def make_tags(tag, word):
    print("<" + tag + ">" + word + "</" + tag + ">")
    return
# example input:
# make_tags('i','Hello world')
# example output:
# <i>Hello world</i>
</syntaxhighlight>
</div>
</div>
[[Category:problem set]]
[[Category:problem set]]
[[Category:python]]
[[Category:python]]
[[Category:strings]]

Latest revision as of 11:42, 22 September 2020

This a problem set for you to work through [1]

This is a problem set. Some of these are easy, others are far more difficult. The purpose of these problems sets are to HELP YOU THINK THROUGH problems. The solution is at the bottom of this page, but please don't look at it until you have tried (and failed) at least three or four times.

The Problem[edit]

This problem is designed to test your skill and knowledge of functions, variables and computational thinking.

You have a simple 10 x 10 grid, with your character at the center (5,5). You can move up, down, left and right. Add:

  • terrain (add water, add hills, add town, add logical terrain (trees should be like a forest, water like a lake)).
  • a bad guy
  • combat
  • basic AI
  • basic statistics for the bad guy (or you) like Hit Points, Armour, Power, etc...

The basic game[edit]

import random
import prettytable
import colorama
from colorama import Fore, Back, Style

grid = []

# let's make our map. We are making a  25 x 25 map
# for our terrain, we are going to randomly insert a number from 1 to 4
#
# 1 is normal ground ...
# 2 is normal ground ...
# 3 is a tree .*.
# 4 is a mountain .^.
# 5 is the player [T]

for i in range(0,625):
    grid.append(random.randrange(1,5))

# now we can manually change our terrain. This code puts a basic mountain range 
# at the very top of our map. 

grid.insert(0,4) 
grid.insert(1,4)
grid.insert(2,4)
grid.insert(3,4)
grid.insert(4,4)
grid.insert(5,4)  
   
     
# now we place the player
     
grid.insert(317,5)

# and let's keep track of where the player is. 

current_player_location = 317


# remember we have a 25 x 25 grid, which we are representing in a simple list. 
# this means row 1 is 0 to 24, row 2 is 25 to 49, row 3 is 50 to 74, etc...
# You should remember this when you work on the move code. 
#    

def draw_board():
    row = 0
    for i in range(0,625):
        if grid[i] == 1:
            print(Style.DIM + Fore.YELLOW + "..." + Style.RESET_ALL ,end='')
        elif grid[i] == 2:
            print(Style.DIM + Fore.YELLOW + "..." + Style.RESET_ALL ,end='')
        elif grid[i] == 3:
            print("." + Fore.GREEN + "*" + Style.RESET_ALL + ".",end='')
        elif grid[i] == 4:
            print("." + Style.DIM + Fore.WHITE + "^" + Style.RESET_ALL + ".",end='')
        elif grid[i] == 5:
            print("[" + Style.BRIGHT + Fore.RED + "T" + Style.RESET_ALL + "]",end='')
        else:
            print("ERR"),
        row = row + 1
        if row == 25:
            print ("\n")
            row = 0 
    return

def move(where_do_you_want_go):
    global current_player_location
    current_player_position = grid.index(5)
    if where_do_you_want_go == "up":
        #
        # let's make sure we are not at the top row, which is 0 to 24
        #
        if grid.index(5) <=25:
            print("You can't go up anymore.")
        elif grid[current_player_position - 25] == 3 or grid[current_player_position - 25] == 4:
            print("You cannot go up, as there is an obstacle in your path!")  
        else:
            print("The player is at position " +  str(grid.index(5)))
            grid[current_player_position - 25] = 5
            grid[current_player_position] = 1
            print("The new player is at position " +  str(grid.index(5)))  
                
    elif where_do_you_want_go == "down":
        current_player_position = grid.index(5)
        #
        # let's make sure we are not at the bottom row, which is 600 to 624
        #
        if grid.index(5) >=600:
            print("You can't go down anymore.")
        elif grid[current_player_position + 25] == 3 or grid[current_player_position + 25] == 4:
            print("You cannot move down, as there is an obstacle in your path!") 
        else:
            print("The player is at position " +  str(grid.index(5)))
            grid[current_player_position + 25] = 5
            grid[current_player_position] = 1
            print("The new player is at position " +  str(grid.index(5)))
       
    elif where_do_you_want_go == "right":
        current_player_position = grid.index(5)
        #
        # let's make sure we are not at the bottom row, which is 600 to 624
        #
        if grid.index(5) % 25 == 24:
            print("You can't go right anymore.")
        elif grid[current_player_position + 1] == 3 or grid[current_player_position + 1] == 4:
            print("You cannot move right, as there is an obstacle in your path!")     
        else:
            print("The player is at position " +  str(grid.index(5)))
            grid.insert(current_player_position + 1, grid.pop(current_player_position))
            print("The new player is at position " +  str(grid.index(5))) 
      
    elif where_do_you_want_go == "left":
        current_player_position = grid.index(5)
        #
        # let's make sure we are not at the bottom row, which is 600 to 624
        #
        if grid.index(5) % 25 == 0:
            print("You can't go left anymore.")
        elif grid[current_player_position - 1] == 3 or grid[current_player_position - 1] == 4:
            print("You cannot move left, as there is an obstacle in your path!")     
        else:
            print("The player is at position " +  str(grid.index(5)))
            grid.insert(current_player_position - 1, grid.pop(current_player_position)) 
            print("The new player is at position " +  str(grid.index(5)))                            
    return

def inventory():
    inventory = {'axe':1, 'pick axe':1, 'food':10}
    inventory_table = prettytable(['Item', 'Quantity'])
    inventory_table.align["Item"] = "l"
    for i,e in inventory.iteritems():
        inventory_table.add_row([str(i), e])
    print(inventory_table)
    foo = input("Press enter to contnue...")
    return


def main():
    while True:
        draw_board()
        print("Your current position is: " + str(grid.index(5)))
        print("Other information should appear here. ")
        print("Up, you see " + str(grid[grid.index(5)-25]))
        print("\n") 
        choice = input("What do you want to do (type help for help) > ")
        if choice == "99":
            break
        elif choice == "help":
            help()
        elif choice == "u":
             move('up')
        elif choice == "r":
             move('right')
        elif choice == "l":
             move('left')
        elif choice == "d":
             move('down')
        elif choice == "i":
            inventory()                          
    return

main()

Take this farther[edit]

You want to go farther?

  • add color to this
  • add many types of different entities (google nethack)
  • move the board to 50 x 50
  • add an option to SAVE / RESTORE a game

Make a decent map.

How you will be assessed[edit]

Every problem set is a formative assignment. Please click here to see how you will be graded

References[edit]