Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
while not done:
baddieAddCounter = 0
baddies = []
score += 1
fact = ""
#GIVES PLAYER A NEW FACT EVERYTIME THEY REACH THE TARGET SCORE
if score < 200:
fact == 'NOTHING'
elif score > 200 and score <= 599:
fact == 'SWAG'
elif score > 600 and score <= 799:
fact == 'brehh'
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Fact: %s' % (fact), font, screen, 10, 40)
pygame.display.update()
Why is this not working? In game, once the players score reaches the target score (ex >200) it's supposed to change the fact (ex. SWAG') to what it says in the 'if' statement but it stays the same because of the 'fact = ""'.
You are not assigning to fact, you are comparing it. What I assume you want is
if score < 200:
fact = 'NOTHING'
elif score > 200 and score <= 599:
fact = 'SWAG'
elif score > 600 and score <= 799:
fact = 'brehh'
Also note, at a score of 200 the player will get a blank fact, as the first condition is only less than 200, and the next is only greater than 200.
You code doesn't set fact when score is 200. You have to check score >= 200 or use
if score < 200:
fact == 'NOTHING'
elif score <= 599:
fact == 'SWAG'
elif score <= 799:
fact == 'brehh'
BTW: you can set face='' before while
fact = ""
baddieAddCounter = 0
baddies = []
while not done:
score += 1
if score < 200:
fact == 'NOTHING'
elif score <= 599:
fact == 'SWAG'
elif score <= 799:
fact == 'brehh'
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Fact: %s' % (fact), font, screen, 10, 40)
pygame.display.update()
EDIT:
#Margius has right. You use == but you need =
fact = ""
baddieAddCounter = 0
baddies = []
while not done:
score += 1
if score < 200:
fact = 'NOTHING'
elif score <= 599:
fact = 'SWAG'
elif score <= 799:
fact = 'brehh'
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Fact: %s' % (fact), font, screen, 10, 40)
pygame.display.update()
Related
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
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I only have to do this:
Take a string entered by the user and print the game grid as in the previous stage.
Analyze the game state and print the result.
Like this:
1. Enter cells: XXXOO__O_ ---------
| X X X |
| O O _ |
| _ O _ | ---------
X wins
The problem is that my program never reaches the elif statements and I donĀ“t know why.
n = input()
number_grid = []
Winner = ""
print("---------")
Cont = {"X": 0, "O": 0, "_": 0} # This will count to check for impossible games
for i in range(0, len(n), 3):
print("|", n[i], n[i+1], n[i+2], "|")
number_grid.append([n[i], n[i+1], n[i+2]])
Cont[n[i]] = Cont[n[i]] + 1
Cont[n[i + 1]] = Cont[n[i + 1]] + 1
Cont[n[i + 2]] = Cont[n[i + 2]] + 1
print("---------")
Impossible = False
if 2 <= Cont["X"] - Cont["O"] or Cont["X"] - Cont["O"] <= -2:
Impossible = True
print("Impossible")
exit()
if Winner == "" and Impossible is False:
for rows in range(0, 3): # Check winner in rows
if number_grid[rows][0] == number_grid[rows][1] == number_grid[rows][2] != "_":
Winner = number_grid[rows][0]
print(Winner, "wins")
for columns in range(0, 3): # Check winner in columns
if number_grid[0][columns] == number_grid[1][columns] == number_grid[2][columns] != "_":
Winner = number_grid[0][columns]
print(Winner, "wins")
if number_grid[0][0] == number_grid[1][1] == number_grid[2][2] != "_": # Check winner in first diagonal
Winner = number_grid[0][0]
print(Winner, "wins")
if number_grid[0][2] == number_grid[1][1] == number_grid[2][0] != "_": # Check winner in second diagonal
Winner = number_grid[0][2]
print(Winner, "wins")
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
Reducing your code down...
Winner = ""
Impossible = False
if Winner == "" and Impossible is False:
# Stuff
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
In your current code, it's not possible for Winner != "" or Impossible != True. So you will never enter the elif statement.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So I've been trying to make this turn-based battle and I ran into a slight issue. I can't seem to use the variables that are defined within the if statement. I tried declaring them global but that didn't work. Is there any way to solve this problem while still using if statements?
Here the code that I'm having issues with:
import time
from random import randint
import copy
health = randint(100, 400)
speed = randint(50, 100,)
damage = randint(50, 200)
totalhealth = copy.deepcopy(health)
def stats():
print("Damage:",damage)
print("Health:",totalhealth, "|", health)
print("Speed:",speed)
if spawn == "mandrake":
spawnh = 200
spawnspeed = 50
spawnspeed = 50
eelement = "earth"
buff = "heal self"
gold = randint(10,20)
ms = 3
x = True
ss = 0
s = 0
ms = 0
m = 0
spawn = "mandrake"
while x == True:
battle = input("""
Inventory(1)
Run(2)
Attack(3)
Defend(4)
Skills(5)""")
stats()
if battle == '3':
if ss > 99 and spawnh > 0:
print(spawn, "dealt", spawndamage)
time.sleep(3)
ss -= 100
health = health - spawndamage
ms += 1
if s >= 100:
print("you dealt", damage)
time.sleep(3)
spawnh = spawnh - damage
s -= 100
if s <= 100 and spawnh > 0:
print("you prepare to attack")
time.sleep(3)
s += speed
if ss <= 100 and spawnh > 0:
print(spawn, "prepares to attack")
ss += spawnspeed
if ss >= 100 and spawnh > 0:
print(spawn, "dealt", damage)
time.sleep(3)
ss = ss - 100
health = health - spawndamage
if health <= 0:
print("you died!")
time.sleep(3)
if spawnh <= 0:
print("you are victorious!")
x = False
if spawnspeed < 100 and spawnh > 0:
print(spawn, "prepares to attack")
ss += spawnspeed
if health <= 0:
print("you died!")
time.sleep(3)
exit()
exit()
if spawnh <= 0:
print("you are victorious!")
x = False
You're trying to access a variable before it's been declared.
You've got if spawn == "mandrake": before you declare spawn, move spawn = "mandrake" above the if statement.
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'm doing a mini-project on Coursera and I can run most parts of my code. However there's an error in the critical part about the game's match or not checking.
# implementation of card game - Memory
import simplegui
import random
# helper function to initialize globals
def new_game():
global turns, state, pairs, cards
turns = 0
state = 0
pairs = []
cards = range(9) * 2
random.shuffle(cards)
# define event handlers
def mouseclick(pos):
# add game state logic here
global turns, state, pairs
pointed = pos[0] // 50
if pointed in pairs:
pass
else:
if state == 0:
state = 1
pairs.append(pointed)
elif state == 1:
state = 2
turns += 1
label.set_text('Turns =' + str(turns))
pairs.append(pointed)
# if cards[pairs[-2]] == cards[[pairs[-1]]:
# flag = True
# else:
# flag = False
else:
state = 1
if flag == False:
del pairs[-2:]
pairs.append(pointed)
# cards are logically 50x100 pixels in size
def draw(canvas):
for n in range(1, 16):
canvas.draw_line((n * 50, 0), (n * 50, 100), 1, 'Green')
for n in pairs:
canvas.draw_line((n * 50 + 25, 0), (n * 50 + 25, 100), 50, 'White')
for n in pairs:
canvas.draw_text(str(cards[n]), (n * 50 + 15, 65), 50, 'Black')
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.set_canvas_background('Red')
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = 0")
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric
I commented out Line 31 to 34 and that's the part where I have a problem. The console keeps telling me Line 31: SyntaxError: bad input (' ') but I think the indentation is correctly made.
Please help me figure out why it's a 'bad input', thanks a lot!
Update:
Thanks to Russell's help, this function works now.
# define event handlers
def mouseclick(pos):
# add game state logic here
global turns, state, pairs, flag
pointed = pos[0] // 50
if pointed in pairs:
pass
else:
if state == 0:
state = 1
pairs.append(pointed)
elif state == 1:
state = 2
turns += 1
label.set_text('Turns =' + str(turns))
pairs.append(pointed)
if cards[pairs[-2]] == cards[pairs[-1]]:
flag = True
else:
flag = False
else:
state = 1
if flag == False:
del pairs[-2:]
pairs.append(pointed)
Your if statement is indented too far.
elif state == 1:
state = 2
turns += 1
label.set_text('Turns =' + str(turns))
pairs.append(pointed)
if cards[pairs[-2]] == cards[pairs[-1]]:
flag = True
else:
flag = False
else:
state = 1
if flag == False:
del pairs[-2:]
pairs.append(pointed)