Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SyntaxError: invalid syntax
#1
Hey, I'm coding a text based game and stumbled upon a problem when debugging the first demo.
I receive this error when running the game:

line 97
SOLVED: False,
^
SyntaxError: invalid syntax

I have no idea what is causing this problem.
The only lines (I think) you have to look into are:

74-81
85-88
94-101 (this line is copy pasted all the way to line 181, but changed strings)


I'm also having problems with l"valid.jobs" at the lines:

274-280
315-230

The error message said something about "valid" not being an existing variable

This is my entire code:

import cmd
import textwrap
import sys
import os
import time
import random

screen_width = 100

##### Player Setup #####
class player():
    def __init__(self):
        self.name = ''
        self.job = ''
        self.hp = 0
        self.mp = 0
        self.status_effects = []
        self.location = 'a1'
        self.game_over = False
myPlayer = player

##### Title Screen #####
def title_screen_options():
    option = input('>')
    if option.lower() == ('play'):
        setup_game()
    elif option.lower() == ('help'):
        help_menu()
    elif option.lower() == ('quit'):
        sys.exit()
                                               #### Try calling the title_screen_options after Invalid Command
    while option.lower() not in ['play', 'help', 'quit']:
        print('Enter a valid command.')
        option = input('>')
        if option.lower() == ('play'):
            setup_game()
        elif option.lower() == ('help'):
            help_menu()
        elif option.lower() == ('quit'):
            sys.exit()

def title_screen():
    os.system('cls')
    print('############################')
    print('# Welcome to the Text RPG  #')
    print('############################')
    print('-Play')
    print('-Help')
    print('-Quit')
    title_screen_options()

def help_menu():
    print('############################')
    print('#        How to play       #')
    print('############################')
    print("-To Move: enter 'up', 'down',")
    print(" 'left', or 'right\n")
    print("-To Inspect: enter 'inspect'\n")
    print("-To Quit: enter 'quit'\n")
    print("          'Back'            ")
    title_screen_options
    ################################################# Add "Back" option #####################################

#### Map ####
#a1                           #Player starts at a1
#------------------
#l x  l     l     l a3
#------------------
#l    l     l     l b3
#------------------
#l    l     l     l c3
#------------------

ZONENAME: 'zonename'
DESCRIPTION: 'description'
EXAMINATION: 'examination'
SOLVED: False
UP: 'up'
DOWN: 'down'
LEFT: 'left'
RIGHT: 'right'

valid = True

solved_places = {'a1': False, 'a2': False, 'a3': False,
                'b1': False, 'b2': False, 'b3': False,
                'c1': False, 'c2': False, 'c3': False,
                }



zonemap = {
    'a1': {
        ZONENAME: 'Desert',
        DESCRIPTION: 'Sun blazing, sand everywhere, Im in middle of a desert',
        EXAMINATION: 'In the distance, a hooded figure with green clothes, sitting on a red carpet hovering above the sand.'
        SOLVED: False,
        UP: '',
        DOWN: 'b1',
        LEFT: '',
        RIGHT:'a2',
    },
    'a2': {
        ZONENAME: 'Desert Mirage',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b2',
        LEFT: 'a1',
        RIGHT:'a3',
    },
    'a3': {
        ZONENAME: 'Desert Village',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b3',
        LEFT: 'a2',
        RIGHT:'',
    },
    'b1': {
        ZONENAME: '',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a1',
        DOWN: 'c1',
        LEFT: '',
        RIGHT:'b2',
    },
    'b2': {
        ZONENAME: '',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a2',
        DOWN: 'c2',
        LEFT: 'b1',
        RIGHT:'b3',
    },
    'b3': {
        ZONENAME: '',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a3',
        DOWN: 'c3',
        LEFT: 'b2',
        RIGHT:'',
    },
    'c1': {
        ZONENAME: '',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b1',
        DOWN: '',
        LEFT: '',
        RIGHT:'c2',
    },
    'c2': {
        ZONENAME: '',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b2',
        DOWN: '',
        LEFT: 'c1',
        RIGHT:'c3',
    },
    'c3': {
        ZONENAME: '',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b2',
        DOWN: '',
        LEFT: 'c2',
        RIGHT:'',
    },

}

##### Game Interactivity #####

def print_location():
    print('\n' + ('#' * (4 + len(myPlayer.location))))
    print('# ' + myPlayer.location + ' #')
    print('#' + zonemap[myPlayer.location] [DESCRIPTION] + ' #')
    print('\n' + ('#' * (4 + len(myPlayer.location))))

def prompt():
    print('\n' + '=========================')
    print('What would you like to do?')
    action = input('>')
    acceptable_actions = ['move', 'go', 'travel', 'walk', 'quit', 'examine', 'inspect', 'interact', 'look',]
    while action.lower() not in acceptable_actions:
        print('Unknown command, try another.\n')
        action = input('>')
    if action.lower() == 'quit':
        sys.exit()
    elif action.lower() in ['move', 'go', 'travel', 'walk']:
        player_move(action.lower())
    elif action.lower() in ['examine', 'inspect', 'interact', 'look']:
        player_examine(action.lower())

def player_move(myAction):
    ask = 'Where would you like to go?\n'
    dest = input(ask)
    if dest in ['up', 'north']:
        destination = ZONENAME[myPlayer.location] [UP]
        movement_handler(destination)
    if dest in ['down', 'south']:
        destination = ZONENAME[myPlayer.location] [DOWN]
        movement_handler(destination)
    if dest in ['left', 'west']:
        destination = ZONENAME[myPlayer.location] [LEFT]
        movement_handler(destination)
    if dest in ['right', 'east']:
        destination = ZONENAME[myPlayer.location] [RIGHT]
        movement_handler(destination)

def movement_handler(destination):
    print('\n' + 'You have moved to the' + destination + '.')
    myPlayer.location = destination
    print_location()

def player_examine(action):
    if ZONENAME[myPlayer.location] [SOLVED]:
        print("It doesn't seem like there is anything noteworthy left here.\nMaybe I should look elsewhere.")
    else:
        print("There's something interessting with this place...")

##### Game Functionality #####

def setup_game():
    os.system('cls')

def main_game_loop():
    while myPlayer.game_over is False:
        prompt()
    # here handle if puzzles has been solved, boss defeated, explored everything...

#### Name Collection
    question1 = "Hello there, what's your name?\n"
    for character in question1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    player_name = input('>')
    myPlayer.name = player_name

    question2 = "player_name + huh...\nYes... I recognize that name but I do not remember where from...\n"
    for character in question2:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)

### Job Handling ####
    question3 = "Well then, tell me...\n Are you a mighty Warrior or a wize Wizard?\n"
    question3added = "(Warrior or Wizard)\n"
    for character in question3:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    for character in question3added:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.1)
    player_job = input('> ')
    valid.jobs = ['warrior', 'wizard']
    if player_job.lower() in valid.job:
        myPlayer.job = player_job                                            
    else:
        while player_job.lower not in valid.jobs:
            player_job = input('> ')
            if player_job.lower() in valid.jobs:
                myPlayer.job = player_job

    question4 = player_name + " the mighty " + player_job + " huh...\n"        #yes or no
    for character in question1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    player_name = input('>')
    myPlayer.name = player_name

    speach1 = "Yes, I do not know why I have your name in my mind...\n"
    speach2 = "But that is not important right now,\n"
    speach3 = player_name + ', '
    speach4 = "tell me... are you wize/strong enough to escape this illusion of mine?"                          # #tell me, are you STRONG/WIZE    (depening on warr or wiz)
    for character in speach1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.03)
    for character in speach2:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    for character in speach3:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.01)
    for character in speach4:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.03)

#### Class Stats
if myPlayer.job == 'warrior':
    player_hp = 100
    player_mp = 20
elif myPlayer.job == 'wizard':
    player_hp = 50
    player_mp = 120


    os.system('cls')
    print('############################')
    print('#    Let the games begin   #')
    print('############################')
    main_game_loop()
Edit: I have one more question, how to I break up code into lines to make it easier to read while coding, right now it's in a single line in python and is hard to read. It looks like this

DESCRIPTION: 'As you continue walking in the desert, there is nothing but sand wherever you look.\nYou feel as if you are in middle of the desert, as far away from anything as possible.\nThirsty, warm, fatigued... you continue wandering through the desert.\n'

#I want it to look like this:
'As you continue walking in the desert, there is nothing but sand wherever you look.\n
You feel as if you are in middle of the desert, as far away from anything as possible.\n
Thirsty, warm, fatigued... you continue wandering through the desert.\n'
Reply
#2
You need a comma at the end of line 96. Syntax errors often don't become syntax errors until the line after the actual problem, so always watch for that.

You define valid.jobs right before checking valid.job. Could the plural be causing the problem?

There are two ways to handle long strings. Multi-line strings (using triple quotes) are a common solution:

text = """It is pitch black.
You are likely to be eaten by a Grue."""
Note that you don't need new line characters, you just use actual new lines. Multi-line strings can mess with your indentation, however. Another solution is that adjacent strings concatenate:

Output:
>>> fred = ('it is pitch black\n' ... 'you are likely to be eatn by a grue.') >>> fred 'it is pitch black\nyou are likely to be eatn by a grue.' >>>
Note the parentheses, you need to make sure the second line is interpreted as part of the first line. The fact that your big string is inside a dictionary should take care of that. You can also use a backslash at the end of each line.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Jesus christ, you have helped me in every single thread I've created. Thank you man
The multi-line string is really gonna come in handy, thank you.

I have stumbled upon a new problem after fixing those bugs.

class player():
    def __init__(self):
        self.name = ''
        self.job = ''
        self.hp = 0
        self.mp = 0
        self.status_effects = []
        self.location = 'a1'
        self.game_over = False
myPlayer = player

def main_game_loop():
    while myPlayer.game_over is False:
        prompt()
This code gives the error (line 13):
Class 'player' has no 'game_over' member. it cleary has at "self.game_over = False"
Reply
#4
'self' is for instance attributes. myPlayer is assigned to player, which is a class, not an instance of a class. If you want to create an instance, do myPlayer = player().
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thank you I think it worked. I have other bugs that popped up so I can't check it out right now

I have another question for myPlayer_job, I want to know if this is a valid statement (if not, how would I write it?)

##### Class Stats #####
if myPlayer.job == 'warrior' == 'mighty warrior':
    player_hp = 100                                     #What I want to do here is, when the player wants to choose his "job" in "Job Handling"
    player_mp = 20                                      #let's say he wants to be a "warrior". If the player were to input "mighty warrior" it would
elif myPlayer.job == 'wizard' == 'mighty wizzard':      #still give him the same class.
    player_hp = 50                                      #First of all, the "if myPlayer.job == 'warrior' == ' mighty warrior':" probably wont work.
    player_mp = 120                                     #If I were to type "print(myPlayer.job)" this would probably give an error.

### Job Handling
question3 = "Well then, tell me...\n Are you a mighty Warrior or a wize Wizard?\n"
    player_job = input('> ')
    valid.jobs = ['warrior', 'wizard']
    if player_job.lower() in valid.jobs:
        myPlayer.job = player_job                                            
    else:
        while player_job.lower not in valid.jobs:
            print('Say again, I did not understand.')
            print('What are you? a Warrior or a Wizard?')
            player_job = input('> ')
            if player_job.lower() in valid.jobs:
                myPlayer.job = player_job
As I'm writing this, I got another bug.
The code below gives the following error:
'a1': {
TypeError: unhashable type: 'dict'

I don't understand what part in the code is an immutable object

ZONENAME = 'zonename'
DESCRIPTION = 'description'
EXAMINATION = 'examination'
SOLVED: False
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'

zonemap = {
    'a1': {
        ZONENAME: 'Desert',
        DESCRIPTION: 'description',
        EXAMINATION: 'examination',
        SOLVED: False,
        UP: '',
        DOWN: 'b1',
        LEFT: '',
        RIGHT:'a2',
    },
    'a1': {
        ZONENAME: 'Desert',
        DESCRIPTION: 'description',
        EXAMINATION: 'examination',
        SOLVED: False,
        UP: '',
        DOWN: 'b1',
        LEFT: '',
        RIGHT:'a2'
    }
}
Reply
#6
The only error I get with that code is on line 4: the colon should be an equals sign.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#7
For checking if one thing is equal to one of two other things, you can use or:

if myPlayer.job == 'warrior' or myPlayer.job == 'mighty warrior':
However, it is generally simpler to use the 'in' operator:

if myPlayer.job in ('warrior', 'mighty warrior'):
Now, you can also use a dictionary:

HP_BY_JOB = {'warrior': 100, 'mighty warrior': 100, 'wizard': 50, 'mighty wizard': 50}
player_hp = HP_BY_JOB[my_player.job]
You could have a similar one for MP. That makes the code a lot simpler when you have a lot of jobs. Another thing you could do is have each job store all of it's base stats:

JOB_STATS = {'warrior': {'hp': 100, 'mp': 20}, 'wizard': {'hp': 50, 'mp': 120}, ...}
my_player.stats = JOB_STATS[my_player.job].copy()
That makes them easier to assign to the player, but it does make them a little harder to get from the player, because my_player.hp is now my_player.stats['hp']. You could use setattr to get around this:

JOB_STATS = {'warrior': {'hp': 100, 'mp': 20}, 'wizard': {'hp': 50, 'mp': 120}, ...}
for stat, value in JOB_STATS[my_player.job].items():
    setattr(my_player, stat, value)
Now it's just my_player.hp again. Just be careful with setattr that there isn't a key in the dictionary that is going to overwrite some important attribute of my_player.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
edit: Jesus christ I might actually be the most stupid person alive. The "prompt()" was not indented in the right way, and I fixed the problem. I actually took like 30 mins of my time to write this. I will leave this for you to read anyway.




Jesus christ man, thank you so much for helping me, I'm going to stick with the 2nd example for now (but keep the others in mid)as I don't want it to become too complicated.

I know I'm really pushing myself as a complete newbie to python, actually to coding in general. I've learned so much the first week of coding and I promest, one day, I'm going to become an indie game developer, and publish games on Steam or Gog or something like that (I'm only 18 so I pretty much got my whole life ahed of me (except the 1/5 I've already wasted)), and you are the person that helped me, when completely new to coding and really had no clue what code.

With that out of the way, I have another problem, yeyeye I know, your pretty much my "free" teacher, I don't even understand why you spend your time to help people on this forum. Am I drunk? Not that much actually.

Anyway, I'm coding my "main_game_loop"
I'm done with the intro ("Whats your name" and "class"). HOWEVER, after the intro is done, the last code ("prompt()") doesn't activate. Instead the loop, keeps looping as if "prompt()" is not in the "main_game_loop"



tl;dr
What I want Python to do is excecute "prompt()", which should print "What would you like to do? (and the rest of prompt aswell). However as stated before, Python acts if "prompt()" is outside the loop for some reason.

This is what my "main_game_loop" looks like at the moment:

def prompt():
    print('What would you like to do?')
    action = input('>')
    acceptable_actions = ['move', 'go', 'travel', 'walk', 'quit', 'examine', 'inspect', 'interact', 'look',]
    while action.lower() not in acceptable_actions:
        print('Unknown command, try another.\n')
        action = input('>')
    if action.lower() == 'quit':
        sys.exit()
    elif action.lower() in ['move', 'go', 'travel', 'walk']:
        player_move(action.lower())
    elif action.lower() in ['examine', 'inspect', 'interact', 'look']:
        player_examine(action.lower())


def main_game_loop():
    while myPlayer.game_over is False:

##### INTRO #####
        question1 = "Hello there, what's your name?\n"
        for character in question1:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)
        player_name = input('>')
        myPlayer.name = player_name

        os.system('cls')                             # Clear

        question2 = player_name + " huh...\nYes... I recognize that name but I do not remember where from...\n"
        for character in question2:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)

### Job Handling
        question3 = "Well then, tell me...\nAre you a mighty Warrior or a wize Wizard?\n"
        for character in question3:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)
        player_job = input('> ')
        if player_job.lower() in valid_jobs:
            myPlayer.job = player_job                                            
        else:
            while player_job.lower not in valid_jobs:

                os.system('cls')
                                                                                                # Fix stuck in loop
                print('Say again, I did not understand.')                                      # Fix print flush and time  https://stackoverflow.com/questions/9246076/how-to-print-one-character-at-a-time-on-one-line
                print('What are you? a Warrior or a Wizard?')
                print('##### This part is bugged, restart game #####')
                player_job = input('> ')
                if player_job.lower() in valid_jobs:
                    myPlayer.job = player_job

        os.system('cls')                         #Clear

        question4 = player_name + " the mighty " + player_job + " huh...\n"                                           #yes or no
        for character in question4:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)

        speach1 = "Yes, I do not know why I have your name in my mind...\n"
        for character in speach1:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)
        speach2 = "But that is not important right now...\n"
        for character in speach2:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)

        os.system('cls')                     #Clear

        speach3 = player_name + ', \n'
        for character in speach3:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)
        speach4 = "tell me... are you wize enough to escape this illusion of mine?\n"                          # #tell me, are you STRONG/WIZE    (depening on warr or wiz)
        for character in speach4:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)
        input('>')
        os.system('cls')
        print("In the blink of an eye, you appear in a place you have never been, as if you were pulled into another dimension.\n")
    
    prompt()
#### Launch Game ####
os.system('cls')
title_screen()       # Tiles_screen() - 'play - main_game_loop -
Reply
#9
This bit:

        speach1 = "Yes, I do not know why I have your name in my mind...\n"
        for character in speach1:
            sys.stdout.write(character)
            sys.stdout.flush()
            time.sleep(0.01)
You do this over and over and over again. One of the other regulars here (I forget which one) has a good rule: "If you do something twice, you should think about making a function for it. If you do something three times, you have to make a function for it."

Now, I'm not a fan of this sort of messing with the computer output, but a function would make it so much easier:

def stutter(text):
    for character in text:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.01)
Then whenever you wanted to print something that way, you could just do stutter("Yes, I do not know why I have your name in my mind...\n"). Me, I would make use of print and mimic it at the same time:

def stutter(*text, sep = ' ', end = '\n'):
    full_text = sep.join(text) + end
    for character in full_text:
        print(character, end = '')
        time.sleep(0.01)
The *text notation is a way to specify an unlimited number of positional arguments. The variable text becomes a tuple of all those arguments.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#10
Thank you!

I tried using the 4th option, but the stuter text would actually "sleep" and not "write" and "flush", even when I wrote it like this

def stutter(*text, sep = ' ', end = '\n'):
    full_text = sep.join(text) + end
    for character in full_text:
        print(character, end = '')
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.01)
So I will use the third option which works perfectly, and I understand every part of that code unlike the 4th option

Thank you man. As for now I don't have any question. So good luck take care. We will probably meet in another thread later.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  print(data) is suddenly invalid syntax db042190 6 1,183 Jun-14-2023, 02:55 PM
Last Post: deanhystad
  SyntaxError: invalid syntax ?? korenron 15 5,714 Jan-25-2022, 11:46 AM
Last Post: korenron
  Invalid syntax with an f-string Mark17 7 7,779 Jan-14-2022, 04:44 PM
Last Post: Mark17
  invalid syntax in my class CompleteNewb 2 1,895 Dec-13-2021, 09:39 AM
Last Post: Larz60+
Exclamation Invalid syntax error(Predict Ethereum Price) lulu43366 2 3,164 Sep-24-2021, 01:24 PM
Last Post: lulu43366
  Unexplained Invalid syntax Error cybertooth 5 3,245 Aug-02-2021, 10:05 AM
Last Post: cybertooth
  [split] SyntaxError: invalid syntax Code_X 3 2,752 May-04-2021, 05:15 PM
Last Post: Yoriz
  Invalid syntax error - need help fixing calgk01 3 3,277 Feb-23-2021, 08:41 PM
Last Post: nilamo
  Invalid syntax using conditionals if - else jperezqu 1 2,331 Jan-13-2021, 07:32 PM
Last Post: bowlofred
  invalid syntax in line 5. Help Asadzangibaloch 2 2,389 Dec-10-2020, 04:26 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020