简体   繁体   中英

string index out of range, monopoly game

I am making a monopoly game and I keep running in to the same error "string index out of range". What I am trying to do with the code is to make it so that it will look through both lists to find out where I landed when I throw the dice and what that street costs. Once it has done that it will take what that street cost - my total balance.

edit (Added the full code of how far I have come, just to make it more clear of what I am trying to do, I saw that I wasn't clear enough.)

here is my code:

import os, random
os.system("CLS")


player = input(" hello, what is your name? ")


while True:
    monopoly = ["Ga" , "Vastralanggatan", "Allmanning", "Hornsgsgatan", "Inkomstskatt", 
   "Sodrastation", "Folkungagatan", "Chans", "Gotgatan", "Ringvagen", "Besokfangelse", 
   "StEriksgatan", "Elverket", "Odengatan", "Valhallavagen", "ostra station", "Sturegatan", 
   "Allmanning", "Karlavagen", "Narvavagen", "Friparkering", "Strandvagen", "Chans", 
   "Kungstradsgardsgatan", "Hamngatan", "Centralstation", "Vasagatan", "Kungsgatan", 
   "Vattenledningsverket", "Stureplan", "Gaifangelse", "GustavAdolfsTorg", "Drottninggatan", 
   "Allmanning", "Diplomatstaden", "Norrastation", "Chans", "Centrum", "Betalalyxskatt", 
   "Norrmalmstorg"]
    Prices = [150 ,  250 , 130 ,  50 , 150 ,  250 , 130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 
     130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 
     130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 130 ,  50]

    dice1 = 0
    dice2 = 0
    generatedNum = 0
    player1_cash = 1500
    dice1 = random.randint (1,6)
    dice2 = random.randint (1,6)
    generatedNum += dice1 + dice2
    generatedNum += 0
    position = monopoly[generatedNum]
    Prices = Prices[generatedNum]
   
player1_throw = input (player + " press any key to throw the dice")
    print( player + " you threw" , generatedNum)

landmark = monopoly[generatedNum]
    print( " you landed on ", landmark)
    buy_landmark = input(" do you want to buy? " + landmark + " J/N ")
    if buy_landmark == "J":
        print (" you have bought",landmark)
        player1_cash -= position[Prices]
        print ("you have", player1_cash, "left"  )

(generatedNum) = 0

what I get error on : player1_cash -= position[Prices]

the error I get:

Exception has occurred: IndexError
    string index out of range
    File "C:\Users\william\Desktop\Visual Studio Code\fixing_errors.py", line 23, in <module>
    player1_cash -= position[Prices]
Prices = Prices[generatedNum]

player1_cash -= position[Prices]

Instead of above try something like:

price = Prices[generatedNum]

player1_cash -= price

Here's an updated version with some tweaks. If you don't want to see the updates, feel free to skip over this post.

import os
import random

# Starting balance for the player
START_BALANCE = 1500

# Number of faces on each die
N_DIE_SIDES = 6

# Monopoly "pieces".
# Note: There are some duplicates in here.
monopoly = [
    "Ga", "Vastralanggatan", "Allmanning", "Hornsgsgatan", "Inkomstskatt", 
    "Sodrastation", "Folkungagatan", "Chans", "Gotgatan", "Ringvagen", "Besokfangelse", 
    "StEriksgatan", "Elverket", "Odengatan", "Valhallavagen", "ostra station",
    "Sturegatan", "Allmanning", "Karlavagen", "Narvavagen", "Friparkering", "Strandvagen",
    "Chans", "Kungstradsgardsgatan", "Hamngatan", "Centralstation", "Vasagatan",
    "Kungsgatan", "Vattenledningsverket", "Stureplan", "Gaifangelse", "GustavAdolfsTorg",
    "Drottninggatan", "Allmanning", "Diplomatstaden", "Norrastation", "Chans", "Centrum",
    "Betalalyxskatt", "Norrmalmstorg",
    ]

prices = [
    150, 250, 130, 50, 150, 250, 130, 50, 150, 250, 130, 
    50, 50, 250, 130, 50, 150, 250 ,130, 50, 50, 250,
    130, 50, 150, 250, 130, 50, 50, 250, 130, 50, 150,
    250, 130, 50, 50, 250, 130, 50,
    ]


# Key-value maps for board item index to piece and piece to cost.
board_spaces = {i:item for i, item in enumerate(monopoly)}
board_values = {k:v for k, v in zip(monopoly, prices)}

# Default starting values.
generated_num = 0 # Total of die rolls
player1_cash = START_BALANCE # Current player cash
current_spot = 0 # Current position on board
purchases = {} # Accumulated purchases.

# Run until true or player cash loses buying power.
while True: # or while player1_cash >= 0:

    # Roll die
    dice1 = random.randint(1, N_DIE_SIDES + 1)
    dice2 = random.randint(1, N_DIE_SIDES + 1)
    # sum of face values
    generated_num = dice1 + dice2

    # Move to next spot on board.
    current_spot += generated_num

    # Divide by modulo of number of spots which
    # will cycle the piece back to the start when it 
    # reaches the end of the board.
    current_spot %= len(board_spaces)


    # Retrieve next monopoly object from pieces 
    current_item = board_spaces[current_spot]

    # Get the cost of that location by item index.
    cost = board_values[current_item]

    # If current cash less cost is less than or
    # equal to zero, exit sim, because you 
    # cannot by anything else.
    if player1_cash - cost <= 0:
        break

    # Check if piece already owned
    # If not, purchase it and deduct cost.
    if not current_item in purchases:
        purchases[current_item] = cost
        player1_cash -= cost

# Print results
print("\n".join(f"{k}: {v}" for k, v in purchases.items()))

Following off of randomers answer, you also have to loop around when the generated num is bigger than the length of the given list. You can throw in a modulo for such a task.

player1_cash = 1500

while player1_cash > 0:
    monopoly = ["Ga" , "Vastralanggatan", "Allmanning", "Hornsgsgatan", "Inkomstskatt", 
   "Sodrastation", "Folkungagatan", "Chans", "Gotgatan", "Ringvagen", "Besokfangelse", 
   "StEriksgatan", "Elverket", "Odengatan", "Valhallavagen", "ostra station", "Sturegatan", 
   "Allmanning", "Karlavagen", "Narvavagen", "Friparkering", "Strandvagen", "Chans", 
   "Kungstradsgardsgatan", "Hamngatan", "Centralstation", "Vasagatan", "Kungsgatan", 
   "Vattenledningsverket", "Stureplan", "Gaifangelse", "GustavAdolfsTorg", "Drottninggatan", 
   "Allmanning", "Diplomatstaden", "Norrastation", "Chans", "Centrum", "Betalalyxskatt", 
   "Norrmalmstorg"]
    Prices = [150 ,  250 , 130 ,  50 , 150 ,  250 , 130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 
     130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 
     130 ,  50 , 150 ,  250 , 130 ,  50, 50,  250 , 130 ,  50]

    dice1 = 0
    dice2 = 0
    generatedNum = 0
    player1_cash = 1500
    dice1 = random.randint (1,6)
    dice2 = random.randint (1,6)
    generatedNum += dice1 + dice2
    position = monopoly[((generatedNum + len(monopoly)) % len(monopoly))]
    price = Prices[((generatedNum + len(monopoly)) % len(monopoly))]
   
    player1_cash -= price

I think this is the proper modulo notation, as I did not double check it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM