IndexError: list index out of range (Python 2.7) - python

Hello I have recently been programming a game and I have come across and IndexError saying 'IndexError: list index out of range' and was wondering if anyone knew why?
class MenuScene(MenuClass):
def __init__(self, surface, engine):
MenuClass.__init__(self, surface)
self.MoonSurvival = engine
self.currentScene = 0
self.scenes = ['CARTER?! CARTER?! ARE YOU THERE?!\nYeah I am here',
'Look there have been sights of hostile alien activity near moon base 4,\n I need you to go and check it out as this could be a problem.\n\nOk I will, where is my rifle?', \
'It is just outside your room tell,\nme when you are ready and I will send you there.,\nGood luck Carter.\n\nThe aim of the game is to survive the alien invasion as long as possible,\nThere are some special drops the aliens can drop.\nThese include, health, shield, superhealth and triple-bullets.' \
'\nBe careful Carter. The aliens do not stay small for long....\n', \
'CONTROLS:\nA and D = Left, Right\nSPACE = Jump\nLeft Mouse Button = Shoot']
def renderText(self):
# split texts at \n (newline)
texts = self.scenes[self.currentScene].split('\n')
for i in range(len(texts)):
textSurface = self.menufont.render(texts[i], 0, (255, 0, 0))
textRect = textSurface.get_rect()
textRect.centerx = SCREEN_WIDTH / 2
textRect.centery = SCREEN_HEIGHT / 2 + i * self.menufont.size(texts[i])[1]
self.surface.blit(textSurface, textRect)
The error appears in the render text area of the code. Here is the nextScene function for the scenes.
def nextScene(self):
if self.currentScene < 4:
# li
self.currentScene += 1
elif self.currentScene == 5:
self.MoonSurvival.resetGame()
self.MoonSurvival.setState(MENU_GAMEFINISH)
else:
self.MoonSurvival.setState(MENU_INGAME)
The Error:
Traceback (most recent call last):
File "F:\My Game\MoonSurvival.py", line 416, in <module>
Game().run()
File "F:\My Game\MoonSurvival.py", line 194, in run
self.menuScene.draw()
File "F:\My Game\menus.py", line 168, in draw
self.renderText()
File "F:\My Game\menus.py", line 202, in renderText
texts = self.scenes[self.currentScene].split('\n')
IndexError: list index out of range
[Finished in 5.8s]

'It is just outside your room tell,\nme when you are ready and I will send you there.,\nGood luck Carter.\n\nThe aim of the game is to survive the alien invasion as long as possible,\nThere are some special drops the aliens can drop.\nThese include, health, shield, superhealth and triple-bullets.' \
It's hard to see with such a long line, but this line does not have a comma on the end. When Python sees two string literals next to each other, it concatenates their contents and treats them as one string. Put in a comma and see if the problem goes away. I recommend putting a comma after the last element of the list too, so you don't forget the comma when you go to add more scenes later.

Related

python-chess AssertionError: san() and lan() expect move to be legal or null, but got {move} in {fen}

I'm trying to create a chess engine using python-chess, but I keep getting the error message:
Traceback (most recent call last):
File "dir/main.py", line 26, in <module>
print(BOARD.san(whiteMove))
File "dir\venv\lib\site-packages\chess\__init__.py", line 2824, in san
return self._algebraic(move)
File "dir\venv\lib\site-packages\chess\__init__.py", line 2837, in _algebraic
san = self._algebraic_and_push(move, long=long)
File "dir\venv\lib\site-packages\chess\__init__.py", line 2842, in _algebraic_and_push
san = self._algebraic_without_suffix(move, long=long)
File "dir\venv\lib\site-packages\chess\__init__.py", line 2878, in _algebraic_without_suffix
assert piece_type, f"san() and lan() expect move to be legal or null, but got {move} in {self.fen()}"
AssertionError: san() and lan() expect move to be legal or null, but got b2b3 in rnbqkbnr/pppppppp/8/8/8/1P6/P1PPPPPP/RNBQKBNR b KQkq - 0 1
Process finished with exit code 1
with "dir" being my project directory.
I have some code to evaluate the best moves:
def getMoves(board: Board):
legalMoves = [move for move in board.legal_moves]
evals = {}
for move in legalMoves:
board.push(move)
#print(board)
#print()
moveEval = evalBoard(board)
evals.update({move: moveEval})
board.pop()
#print(board)
#print()
print(board.fen())
return evals
Printing out the board results in the same board as the start of the function, meaning its not fully changed. But the FEN string is the string of the board that would be created if I pushed the UCI move to the board.
Nevermind, I found it. Turns out I was messing up my evals!

Renpy ELIF statement

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.

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

Creating a game using pyglet (sprites in particular)

Im currently in an intro coding class and for my final project, i am trying to learn the pyglet module to create a game with a picture in the background, and have a character on the left that a user can make jump, and then have jumps come from the right at a set speed that the user will jump over. i need to use classes for the assignment, and im really having a hard time using creating a sprite class. heres my current code:
import pyglet
window = pyglet.window.Window(700,700)
image = pyglet.image.load('IMG_3315.jpg')#use 10x10 in. image
#image_2 = pyglet.image.load('IMG_3559.jpg')
main_batch = pyglet.graphics.Batch()
score_label = pyglet.text.Label(text="Score: 0", x=570, y=650, batch=main_batch)
the_jump = pyglet.image.load("jumpsi.png")
#horse = pyglet.sprite.Sprite(image_2, x = 50, y = 50)
# background_sound = pyglet.media.load(
# 'Documents/Leave The Night On.mp3',
# streaming=False)
class Jump(pyglet.sprite.Sprite):
def __init__(self, img, x=0, y=0, blend_src=770, blend_dest=771, batch=None, group=None, usage='dynamic', subpixel=False):
self.img = the_jump
self.x = 50
self.y = 50
def draw(self):
self.draw()
# verticle = Jump('verticle')
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
main_batch.draw()
window = Jump()
#horse.draw()
#background_sound.play()
if __name__ == "__main__":
sprite = Jump()
pyglet.app.run()
i know its probably wrong but everything else i have tried (using preexisting games as examples) hasn't worked either.
my current error message is:
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump()
TypeError: __init__() takes at least 2 arguments (1 given)
im just really stuck and have been trying to figure this out for hours and not made any leeway. any help you can offer would be greatly appreciated. Thanks so much!
UPDATE: i recently changed the code, noticing the problem that Gustav pointed out, and change the end call to
if __name__ == "__main__":
sprite = Jump(the_jump)
pyglet.app.run()
but now i get the error
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump(the_jump)
File "jumper.py", line 21, in __init__
self.x = 50
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 459, in _set_x
self._update_position()
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 393, in _update_position
img = self._texture
AttributeError: 'Jump' object has no attribute '_texture'
The error message is telling you exactly which line the error is in and exactly what is wrong. You are initializing the Jump class without passing in an argument for the required parameter img.
You can fix this by either changing the initialization method or your call to Jump().
Here's an example for how to read Python's traceback.

Categories

Resources