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.
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 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 1 year ago.
Improve this question
I am programming code for a squash game scoring system and already return 2 values. If i return another value it would mess up other functions in my code. So i am wondering if there is any way to access the pointCount value outside of the function without returning it?
I don’t recommend doing this, but a quick way is to use a global variable, you will have to declare it first
pointCount = 0
def eng_Game(ra,rb):
global pointCount
win = False
winCondition = 9
aServer = False
bServer = False
aScore = 0
bScore = 0
serverNum = random.randint(1,2)
if serverNum == 1:
aServer = True
else: bServer = True
while win == False:
pointCount += 1
ProbAWin = ra/(ra+rb)
ProbBWin = rb/(rb+ra)
ranNum = random.random()
if ranNum < ProbAWin and aServer:
aScore += 1
elif ranNum < ProbAWin and aServer == False:
aServer = True
bServer = False
elif ranNum > ProbAWin and bServer:
bScore += 1
elif ranNum > ProbAWin and bServer == False:
bServer = True
aServer = False
if aScore == winCondition or bScore == winCondition:
return aScore,bScore
elif aScore == 8 and bScore == 8:
playTo = random.randint(1,2)
if playTo == 1:
winCondition = 10
You will be able to access it using the pointCount variable outside the function now.
The proper way to do this would be to declare a class and initialise variables inside the class, then use the self.variable names to access and modify them. This is a good place to start, https://www.w3schools.com/python/python_classes.asp the syntax is quite easy to understand.
A possible solution is to have a global variable outside the function and change it inside the function for example
pointCount = 0
def engGame(ra,rb):
global pointCount # define pointCount as a global variable
# the rest of the function
engGame(a, b)
# pointCount will be changed here
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.
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
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()