Renpy ELIF statement - python

I have been looking at renpy's tutorial on how to make choices, and for the most part, have it figured out except for one minor thing.
How do I correctly use an elif statement?
I have looked up basic python elif statements and even an actual site on how to use one in renpy and can't get it to work.
(I have attached a screenshot of my code along with my error, any help is greatly appreciated)
Here is a snippet of my code:
define e = Character("???")
$ mage = False
$ warrior = False
$ archer = False
# The game starts here.
label start:
# Show a background.
scene bg black
# This shows a character sprite.
show weird orb
# These display lines of dialogue.
e "Welcome human, what is your name?"
python:
name = renpy.input(_("What's your name?"))
name = name.strip() or __("John")
define m = Character("[name]")
e "Hmm, [name] is it?"
e "That's a wonderful name!"
m "Where am I?"
e "You'll know in good time, my child."
e "For now, tell me a bit about yourself"
menu:
e "Which of these do you prefer?"
"Magic":
jump magic
"Brute Force":
jump force
"Archery":
jump archery
label magic:
e "You chose magic."
$ mage = True
jump enter
label force:
e "You chose brute force."
$ warrior = True
jump enter
label archery:
e "You chose archery."
$ archer = True
jump enter
label enter:
if mage:
m "I'm a mage."
elif warrior:
m "I'm a warrior."
else:
m "I'm an archer"
return
Here's a copy of the error:
I'm sorry, but an uncaught exception occurred.
While running game code:
File "game/script.rpy", line 66, in script
if mage:
File "game/script.rpy", line 66, in <module>
if mage:
NameError: name 'mage' is not defined
-- Full Traceback ------------------------------------------------------------
Full traceback:
File "game/script.rpy", line 66, in script
if mage:
File "C:\Users\ArceusPower101\Downloads\renpy-7.0.0-sdk\renpy\ast.py", line 1729, in execute
if renpy.python.py_eval(condition):
File "C:\Users\ArceusPower101\Downloads\renpy-7.0.0-sdk\renpy\python.py", line 1943, in py_eval
return py_eval_bytecode(code, globals, locals)
File "C:\Users\ArceusPower101\Downloads\renpy-7.0.0-sdk\renpy\python.py", line 1936, in py_eval_bytecode
return eval(bytecode, globals, locals)
File "game/script.rpy", line 66, in <module>
if mage:
NameError: name 'mage' is not defined
Windows-8-6.2.9200
Ren'Py 7.0.0.196
Test 1.0
Thu Aug 23 02:06:20 2018

Your code is giving you an exception because these three lines are never run:
$ mage = False
$ warrior = False
$ archer = False
They don't run because they appear above the start: label, which is where the code starts running.
There are a few ways to fix the issue. One is to simply rearrange the code so that the start label appears above those lines. Another option is to use a default statement for each of the assignments:
default mage = False
default warrior = False
default archer = False
The default statements will be run once when the game starts and when a game is loaded, but only if the variable isn't already defined.

Related

Why am I getting an error whenever I run my function?

import turtle
def replaygame():
replay_label = turtle.Turtle()
replay_label.speed(0)
replay_label.color("White")
replay_label.penup()
replay_label.setposition(-290,280)
againornot = replay_label.textinput("Do you want to play again Y/N ?",False, align = "right", font = ("Arial" , 20, "normal"))
if againornot == Y:
True
else:
False
replaygame()
I'm not sure what the problem is. I imported turtle and I went through it twice. Here's the error I'm getting:
Traceback (most recent call last):
File "/Users/nn/Documents/sfgh.py", line 189, in <module>
replaygame()
File "/Users/nn/Documents/sfgh.py", line 158, in replaygame
againornot = replay_label.textinput("Do you want to play again Y/N ?",False, align = "right", font = ("Arial" , 20, "normal"))
AttributeError: 'Turtle' object has no attribute 'textinput'
When you have a minute, please post your error. In the meantime, I presume the error stems from here:
Try editing this line to put quotes around the Y. againornot == ’Y’
(Apologies for poor the formatting, I’m using my phone.)
Try it like this :
import turtle
def replaygame():
replay_label = turtle
replay_label.speed(0)
replay_label.color("White")
replay_label.penup()
replay_label.setposition(-290,280)
againornot = replay_label.textinput('Play Again', "Do you want to play again Y/N ?")
if againornot == Y:
True
else:
False
replaygame()

error: " type object 'world_load' has no attribute 'split' "

i try to make a game BUT I can not get the world load to work
fings that cud be gud to no
the var update is for the while loop
the error is in the area wer the block gets pikt and displayd.
class world_load:
def __init__(self, line):
self.type = line[0]
self.x = line[1]
self.y = line[2]
def __str__(self):
return self.type+" "+self.x+" "+self.y
with open(fillName, encoding=encoding) as file:
file.readline()
for line in file.readlines():
line = line.strip()
line = line.split(" ")
w = world_load(line)
world.append(p)
while update:
#input
for event in pygame.event.get():
if event.type == pygame.QUIT:
update = False
dis.fill(sky)
for world_load in world:
wo = world_load.split(" ")
if wo[0] == block_grass:
block_grass(wo[1],wo[2])
it's wos not the hole code
hear is the error fing:
Traceback (most recent call last):
File "C:\Users\Deltagare\Desktop\program\Game\Game.py", line 68, in <module>
wo = world_load.split(" ")
AttributeError: type object 'world_load' has no attribute 'split'
First, it is very hard to read your question because you have used poor grammar and spelling. secondly the .split() function in python is used for strings to split them into an array (list). You might be attempting to split your own class which is not a string and will not work. Or you could be attempting to call the split function within your class (This is what Python thinks you are trying to do) and will also not work because there is no split function. It is unclear what you are asking. I advise you rewrite this question to a higher standard and then people will be more able to help.

Adding Score Clock to Game in Python

I have my code for a game here. I have commented out the displayScore(score) call in the main function to allow the program to run. When that call is uncommented the program window closes immediately after opening.
The objective of the function displayScore is to display the game score in the top left corner. Which also needs to be displayed in the right corner for the opposing player's score.
Here is the code for the game with displayScore commented out in the main function so you can run the game and everything will work. Uncomment it to see where the problem is:
ball = ballmovement(ball, ballDirX, ballDirY)
ballDirX, ballDirY = collisionwithedges(ball, ballDirX, ballDirY)
score = checkscore(paddle1, ball, score, ballDirX)
ballDirX = ballDirX * collisionwithpaddles(ball, paddle1, paddle2, ballDirX)
pygame.display.update() #updates the display to clear surface per the frame rate
FRAMECLOCK.tick(FRAMERATE) #Sets the Frames of program to defined rate
if __name__=='__main__':
main()
Just replace the line
displayScore(score)
By:
displayScore(str(score))
You are trying to use a number instead of a string to the argument of render ;) Score is an int and BASICFONT.render((score), True, WHITE)
asks for score to be a string or an array of bytes :)
I found the solution only by reading the console output which was a good indication ^^
Traceback (most recent call last):
File "test.py", line 130, in <module>
main()
File "test.py", line 118, in main
displayScore(score)
File "test.py", line 71, in displayScore
resultSurf = BASICFONT.render((score), True, WHITE)
TypeError: text must be a unicode or bytes

Import Error: no module named

Hi I'm VERY new to programming, and I am working on my first program. I've been following along in a book and I decided to stop and test a function. The function is in a file called myPythonFunctions.py. I then created a new file called untitled.py and put it in the same folder as myPythonFunctions.py.
In untitled.py I have the following code:
import myPythonFunctions as m
m.generateQuestion()
Very simple, but when I try to run it I get Import Error: no module named myPythonFunctions.
I don't understand, there is clearly a file named myPythonFunctions in the folder. What's going on?
In case you need it, here is the code for m.generateQuestion()
def generateQuestion():
operandList = [0,0,0,0,0,]
operatorList = ['', '', '', '', '']
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0,4):
if index > 0 and operatorList[index-1] !='**':
operator = operatorDict[randint(1,4)]
else:
operator = operatorDict[randint(1,3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1,5):
questionString = questionString + OperatorList[index-1] + str[operandList[index]
result = eval(questionString)
questionString.replace("**","^")
print('\n' + questionString)
userAnswer=input('Answer: ')
while true:
try:
if int(userAnswer) == result:
print('Correct!')
return 1
else:
print('Sorry, the correct answer is', result)
return 0
except Exception as e:
print("That wasn't a number")
userAnswer = input('Answer: ')
Edit: I'm now getting this error
Traceback (most recent call last):
File "/Users/Brad/Desktop/Python/Untitled.py", line 1, in <module>
import myPythonFunctions as m
File "/Users/Brad/Desktop/Python/myPythonFunctions.py", line 33
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
^
SyntaxError: invalid syntax
The syntaxis error you are getting, is because you are trying to define a dictionary as a list, so the interpreter is raising the error because it does not know what to do with that.
To define a dictionary you need to use { } instead of [ ]
--- EDIT 2
Your dictionary implementation is wrong, do you really copied this code from somewhere?
The
operatorDict = {1:'+', 2:'-', 3:'*', 4:'**'}
Your code was mispelled
---- EDIT
Your code on myPythonFunctions is really bad.
Python needs correct identation to works, please double check this step
I suggest you to do a check in your structure:
I did this right now
/somefolder
--this.py
--functions.py
/
The contents
--this.py
import functions as f
print f.hello()
--functions.py
def hello():
return 'It worked'
Try this structure in your environment :D
And then run:
python this.py

Python syntax error (in the interpreter) after a for loop

I'm running some python code (pasted in) from the console, and getting an unexpected result. Here's what the code looks like:
parentfound = False
structfound = False
instruct = False
wordlist = []
fileHandle = open('cont.h')
for line in fileHandle:
if line is "":
print "skipping blank line"
continue
if "}" in line:
instruct = False
index = line.index("}")
wordlist.append(word)
pass
try:
print wordlist
except Exception as e:
print str(e)
After the for loop, I'd like to print the wordlist. No matter what I do, I can't include anything outside the for loop. Here's the error I receive:
... if "}" in line:
... instruct = False
... index = line.index("}")
... wordlist.append(word)
... pass
... try:
File "<stdin>", line 10
try:
^
SyntaxError: invalid syntax
It occurs whether I type the code by hand into the terminal or if I paste it in. I'd appreciate any help you can offer. Thank you!
The ... prompt in the REPL means that it still hasn't finished the previous block. You will need to press Enter on an empty line to terminate it first.

Categories

Resources