Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
class Snake(object):
def __init__(self, size):
self.size = size
self.board = []
self.snake = []
self.food = []
self.score = 0
def move(self, direction):
if direction in "UP, DOWN, LEFT, RIGHT":
self.board[self.snake[0]][self.snake[1]] = direction
self.snake = self.snake[1:] + [self.snake[0]]
def eat(self, food):
if food == "right":
self.score += 1
elif food == "left":
self.score -= 1
def checkCollision(self, other):
if self.snake[0] == other.snake[0] and self.snake[1] == other.snake[1]:
print("Oops, you hit yourself!")
elif self.snake[0] == other.snake[1] and other.snake[0] == self.snake[1]:
print("Oops, you hit the wall!")
else:
print("Collision")
if __name__ == "__main__":
snake = Snake(5)
print("You are playing as: " + snake.name)
while snake.score >= 0:
print("You have " + snake.score + " points left.")
print("moving snake")
snake.move("left")
print("Current board:")
print(snake.board)
print("Eating food")
snake.eat("left")
print("Current board:")
print(snake.board)
The Problem is with line 37
elif food == "left":
I'm getting a syntax error: invalid syntax and I am not sure how to go about fixing this specific error. I am new to programming in python and this should probably be obvious to someone more experienced I am hoping. For me I can't seem to figure it out.
Python relies on indentation for its blocks. Multiple of your lines aren't indented properly.
if food == "right":
self.score += 1
elif food == "left":
self.score -= 1
Make sure to indent your code. There are other parts of the code that aren't indented properly such as checkCollision and your if __name__ == "__main__"
You have an indentation problem with your code. You can find out more about it here.
You should just add tabulation in elif food == "left"
when using il and elif use it in this way (if and elif in the same degree of space)
if condition:
do something
elif condition:
do something
Related
I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a random shape out of list of the main 7 shapes and every time the user presses "a" it changes the left facing gif of that shape using the giant el if wall. However, we ran unto an error where instead of executing the elif statements, it just skips to the last line and changes to the J shape no matter what shape was called in the random statement. Any help would be awesome, thank you! (We are still learning btw) also the rotate function is also supposed to happen when the user presses the "d" key but its supposed to change to the other direction.
import turtle as trtl
import random as rand
wn = trtl.Screen()
#configurations
tetris = trtl.Turtle()
drawer = trtl.Turtle()
background = trtl.Turtle()
starty = int(-400)
square = ("sqaure_block.gif")
s_block_normal = ("S_block_norm.gif")
s_block_standing = ("S_block_right.gif")
invert_s_block_normal = ("Z_block_norm.gif")
invert_s_block_standing = ("Z_block_right.gif")
l_block_normal = ("L_block_norm.gif")
l_block_180 = ("L_block_180.gif")
l_block_right = ("L_block_right.gif")
l_block_left = ("L_block_left.gif")
line_normal = ("line_block_norm.gif")
line_standing = ("line_block_standing.gif")
t_block_normal = ("T_block_norm.gif")
t_block_180 = ("T_block_180.gif")
t_block_right = ("T_BLOCK_RIGHT.gif")
t_block_left = ("T_block_left.gif")
j_block_normal = ("J_block_norm.gif")
j_block_180 = ("J_block_180.gif")
j_block_right = ("J_block_right.gif")
j_block_left = ("J_block_left.gif")
wn.addshape (square)
wn.addshape(s_block_normal)
wn.addshape(s_block_standing)
wn.addshape(invert_s_block_normal)
wn.addshape(invert_s_block_standing)
wn.addshape(l_block_normal)
wn.addshape(l_block_180)
wn.addshape(l_block_right)
wn.addshape(l_block_left)
wn.addshape(line_normal)
wn.addshape(line_standing)
wn.addshape(t_block_normal)
wn.addshape(t_block_180)
wn.addshape(t_block_right)
wn.addshape(t_block_left)
wn.addshape(j_block_normal)
wn.addshape(j_block_180)
wn.addshape(j_block_right)
wn.addshape(j_block_left)
Tshape = [square, s_block_normal, invert_s_block_normal, l_block_normal, line_normal, t_block_normal, j_block_normal]
squarecor = [-50, -25, -100, -50]
wn.bgcolor("lightblue")
background.speed("fastest")
background.hideturtle()
background.pu()
background.goto(-400,-200)
background.fillcolor("blue")
background.pencolor("blue")
background.begin_fill()
background.pd()
background.goto(400,-200)
background.goto(400,-350)
background.goto(-400,-350)
background.goto(-400,-200)
background.end_fill()
#sprite direction change
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
'''
def (fast_down):
global tetris
tetris.setheading(270)
tetris.forward(10)
'''
#turn right
def turn_right():
tetris.speed("fastest")
tetris.setheading(0)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#turn left
def turn_left():
tetris.speed("fastest")
tetris.setheading(180)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#down
#tetris container/backround
drawer.pensize(5)
drawer.speed("fastest")
drawer.penup()
drawer.goto(150, 200)
drawer.pendown()
drawer.setheading(270)
drawer.forward(400)
drawer.setheading(180)
drawer.forward(300)
drawer.setheading(90)
drawer.forward(400)
drawer.hideturtle()
#game WIP!!!!!!!!!!
y = 0
space = int(1)
tracer = True
def spawn_T():
new_T=rand.choice(Tshape)
tetris.shape(t_block_180)
tetris.pu()
tetris.goto(0, 200)
tetris.setheading(270)
tetris.forward(10)
'''
if ((abs(space - starty)) < 200):
tetris.forward(2)
else:
'''
tetris.stamp()
'''
space = space =+ 1
'''
tetris.hideturtle()
tetris.goto(0,200)
tetris.showturtle()
if (y == 0):
spawn_T()
#changeing the directions of the sprites
#events
wn.onkeypress(turn_right, "Right")
wn.onkeypress(turn_left, "Left")
wn.onkeypress(sprite_right, "a")
wn.onkeypress(sprite_left, "d")
'''
wn.onkeypress(fast_down, "s")
'''
wn.listen()
wn.mainloop()
Here is the google drive file https://drive.google.com/drive/folders/1Q_zXEqm4aFHQ4RV-ZvEXCK2Wi7SHMxrW?usp=share_link
I think the indentation is wrong here. Maybe try putting the last else-statement one tab further?
Please use elif instead of the else: if formulation to get away from the bewildering indentation - here's how it should look:
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
That said, because this is all the code you've provided, it's not possible to run it and examine why it's not working. Can you please provide an example of an implementation of these functions?
According to the documentation, shape() returns the current shape with no parameters, and sets it with one parameter. Therefore in:
if tetris.shape(s_block_normal):
shape(name) returns None, which is always False. So, if you change to:
if tetris.shape() == s_block_normal:
It should function as required.
Also, you can get rid of the if ladder completely by, for instance, something like:
next_left_shape = {s_block_normal: s_block_standing,
invert_s_block_normal: invert_s_block_standing,
... }
tetris.shape(next_left_shape[tetris.shape()])
I am coding a simple maze game. I've created a Player class with a move method -- but whenever I want to check if the move is in the available paths list, it does run the move method and changes my character position.
class Player :
def __init__ (self, position):
self.position = position
def move (self, direction):
if direction == "right": self.position[0] += 1
elif direction == "left": self.position[0] -= 1
elif direction == "up": self.position[1] -= 1
elif direction == "down": self.position[1] += 1
return self.position
maze_paths = [[0,0], [1,0]]
mac = Player([0,0])
direction = 'left'
if mac.move(direction) in maze_paths:
print('ok')
else:
print('No way!')
print('Final position is: %r' % (mac.position))
The output I expect is:
No way!
Final position is: [0, 0]
...because the move left shouldn't be allowed with the maze as it's defined. However, what we have instead is:
No way!
Final position is: [-1, 0]
...with the move happening even though it shouldn't be allowed.
As #TimRichardson suggested in the comments, the act of calculating state should be split out from the act of changing state. Functional programming languages are built to make this easy, but Python isn't one -- so you need to jump through some hoops.
Consider splitting move into two methods, like the calculate_move and do_move shown below:
class Player:
def calculate_move(self, direction):
"""Calculate where we would be if we moved in a direction"""
emulated_position = self.position[:] # make a copy
if direction == "right": emulated_position[0] += 1
elif direction == "left": emulated_position[0] -= 1
elif direction == "up": emulated_position[1] -= 1
elif direction == "down": emulated_position[1] += 1
return emulated_position
def do_move(self, direction):
"""Actually move in the given direction"""
self.position = self.calculate_move(direction)
maze_paths = [[0,0], [1,0]]
mac = Player([0,0])
direction = 'left'
if mac.calculate_move(direction) in maze_paths:
mac.do_move(direction)
print('ok')
else:
print('No way!')
print('Final position is: %r' % mac.position)
...which properly emits as output:
No way!
Final position is: [0, 0]
Create a meningful separate validate function like. Did this on my phone.
def validateMove(direction):
if direction == "right":
return self.position[0] + 1 in self.maze_paths
if direction == "down":
return self.position[1] + 1 in self.maze_paths
if direction == "left":
return self.position[0] - 1 in self.maze_paths
if direction =="up":
return self.position[1] - 1 in self.maze_paths
return false
So I've been working on this game (I'm a big noob at python and I've only worked on this for like 3 days) and I've been trying to move the Location (Add or Subtract one from Location's x and y values) but the fuction doesn't work. I know because I put a print in the function and the print didn't work at all. What is wrong? (I have created a folder for this project and there is a folder called Decisions containing 2 files.)
Locations.py:
class Location:
def __init__(self, x, y):
self.x = x
self.y = y
def move_forward(self):
self.y = self.y + 1
return self.y
def move_back(self):
self.y = self.y - 1
return self.y
def move_left(self):
self.x = self.x - 1
return self.x
def move_right(self):
self.x = self.x + 1
return self.x
main.py (Main Function):
import Decisions
import Characters
import Locations
def main():
Player = Characters.Character([], 100)
Loc = Locations.Location(0, 0)
answer = Decisions.choice_yes_no.choice_yes_no("You woke up, discovering
that somehow you were in the middle of a dark dungeon. A sword lies to the
left of you, pick it up? (Yes/No) ")
if answer == True:
print("You picked up the sword.")
Player.add_item("Sword")
elif answer == False:
print("You chose not to pick up the sword.")
answer_2 = Decisions.choice_direction.choice_direction("You stood up,
patting the dust off your clothes, you looked around. The room was dark and
you view was limited to a few meters. Where do you go?
\n(Left/Right/Forward/Back) ")
if answer == "forward":
Loc.y = Loc.y + 1
elif answer == "back":
Loc.move_back()
elif answer == "left":
Loc.move_left()
elif answer == "right":
Loc.move_right()
print(Loc.x)
print(Loc.y)
main() #REMOVE BEFORE USING#
The function add_item works just fine, what is wrong? There aren't any errors, it's just when I print the x and y values at the end they stay 0.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
New to python (1st semester), I have a game that I am working on for my final project. I have written the code to do all I want for a "level" but I need to know how to make it start a new level if a condition is met. If I have a while loop already, should I create another loop outside for the level? (first post, so i'm not certain if this is enough info.) Thank you for anything you can provide.
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if (pygame.key.get_pressed()[pygame.K_RIGHT] != 0 ):
newbasketx = basketx + 15
if newbasketx <= 600:
basketx = newbasketx
if (pygame.key.get_pressed()[pygame.K_LEFT] != 0 ):
newbasketx = basketx - 15
if newbasketx >= 0:
basketx = newbasketx
basket_rect = pygame.Rect(basketx, baskety, 200, 70)
for index in range (0,nFruits):
fruity[index] = fruity[index] + fruitSpeed[index]
thisFruit_rect = pygame.Rect (fruitx[index], fruity[index],150,75)
if thisFruit_rect.colliderect (basket_rect):
fruity[index] = random.randrange (-1000, -10)
fruitx[index] = random.randrange (0,600)
thisFruit = fruitList[index]
if thisFruit == badpear:
life = life -1
if thisFruit == banana:
score = score + 5
totalScore = totalScore + 5
if thisFruit == apple:
score = score + 10
totalScore = totalScore + 10
if thisFruit == cherry:
score = score + 15
totalScore = totalScore + 15
if thisFruit == grapes:
score = score + 1
totalScore = totalScore + 1
elif fruity[index] > height:
fruity[index] = random.randrange (-1000, -10)
fruitx[index] = random.randrange (0,600)
fruitMiss = fruitMiss + 1
if fruitMiss == 10:
life = life - 1
fruitMiss = 0
if life == 0:
print 'game over'
break
screen.fill(LIME)
for index in range (0,nFruits):
screen.blit(fruitList[index],(fruitx[index],fruity[index]))
screen.blit(basket, (basketx, baskety))
pygame.display.update()
if score >= 100:
life = life + 1
score = 0
pygame.time.delay(15)
print 'total', totalScore, 'Score', score, 'Life', life, 'miss',fruitMiss
without knowing your specific structure this is very hard to answer. however, you could do something like this:
while level == 1:
[do level 1 stuff]
while level == 2:
[do level 2 stuff]
etc.
you can use break to exit a while loop if the level is no longer the same.
See here for more information about control structures in python!
You can use the break or continue statements to go out of your loop or in the next loop, see here for a short introduction.
I am new to programming in python and, I started writing a simple text based adventure game. I came across a problem when passing an object from one function to another. Here is my code:
import random
import time
num = random.randint(0,2)
xp1 = random.randint(1,2)
class player:
def __init__ (self, name, health, strength, defense, potion, xp, level):
self.__health = health
self.__strength = strength
self.__defense = defense
self.__name = name
self.__potion = potion
self.__xp = xp
self.__level = level
def getName(self):
return self.__name
def getHealth(self):
return self.__health
def getStrength(self):
return self.__strength
def getDefense(self):
return self.__defense
def getPotion(self):
return self.__potion
def getXP(self):
return self.__xp
def getLevel(self):
return self.__level
def setHealth(self):
self.__health = 10
def setLevel(self):
self.__level = 1
def subHealth(self, num):
self.__health -= num
def subPotion(self):
self.__potion -= 1
return self.__health
def addPotion(self, num1):
self.__potion += num1
def addHealth(self):
self.__health +=2
def addStrength(self):
self.__strength += 1
def addDefense(self):
self.__defense += 1
def addXP(self):
self.__xp += xp1
def addLevel(self):
self.__level += 1
self.__addHealth += 1
self.__defense += 1
self.__strength += 1
def battle(enemy, player1, name1):
player1 = player(name1, player1.getHealth(), player1.getStrength(), player1.getDefense(), player1.getPotion(), player1.getXP(), player1.getLevel())
enemy = player('Dongus', enemy.getHealth(), enemy.getStrength(), enemy.getDefense(), enemy.getPotion(), enemy.getXP(), enemy.getLevel())
s = 0
while s == 0:
time.sleep(1)
attack =int(input("Type 1 to attack, type 2 to use a potion."))
if attack == 1:
time.sleep(1)
print("Dongus's health is", enemy.subHealth(num))
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
elif attack == 2:
time.sleep(1)
print("You used a potion.")
player1.addHealth(), player1.subPotion()
if player1.getHealth() > 10:
player1.setHealth()
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
if enemy.getHealth()<=0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
time.sleep(1)
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
time.sleep(2)
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player('Dongus', 8, 4, 0, 0, 0, 0)
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player1.getDefense())
time.sleep(2)
print("Fight!")
pick = input("You found a health potion! Press 'p' to pick it up.")
p = 0
while p == 0:
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion(1)
p = 2
else:
print("You have no potions, you should probably pick this one up.")
player1.addPotion(1)
p = 2
battle(enemy, player1, name1)
if self.__getXP() == 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player.getDefense())
loot1 = int(input("Type ''1'' to loot the enemy chest."))
if loot1 == 1:
print("You recieved two potions!")
player1.__addPotion(2)
enemy.setHealth(10)
battle(enemy, player1, name1)
main()
Now the problem is when I run the game, I get to a point where I type "1" to attack the enemy, but it says, for some reason, that after attacking the enemy, the enemies health is at "None". This is the same case when the enemy attacks player1, it says player1's health is at "None". I assume that "None" is the default value in python 3.4.1, so my thinking is that the player1's object from def main() are not being transferred over to def battle() and I cannot see the reason why this is happening. I most likely am missing something here, or it is something I do not already know about Python that is causing the issue. Does anybody know what I can do to fix this, and why it is doing this?
BTW some of the terms I am using may be wrong, so please correct me if they are... I have only been coding for 2 weeks :p.
Thanks!!!
First, received not recieved
2nd yes, If you have a Python function that does not return a value, the result is None
# dummy will return "Positive" or None
def dummy(x):
if X > 0:
return "Positive"
So, you probably want to change
def subHealth(self, num):
self.__health -= num
to
def subHealth(self, num):
self.__health -= num
return self.__health
Your question re: the "player" classes from def main() are not being transferred over to def battle() does not really make sense to me.
But, I see that in the first 2 lines of battle, you are replacing the formal parameters player1 and enemy with local variables, this seems like odd usage in your program.