Reputation: 43
I have two variables: "score" and "bonus", both initialized to 0. Every time score increases by 5, I want the bonus to increase by 1. I've tried using itertools.repeat, but I can't make it work.
Initial idea: If the score is a multiple of 5, and is at least 5, then increment the bonus by 1.
if score>=5 and score%5==0:
bonus += 1
Unfortunately, this doesn't work, since we continue to increment the bonus forever. In other words, when the score is 5, the bonus becomes 1 . . . then 2 . . . and so on, without bound.
Idea: keep track of the score; if the score is a multiple of 5, and is at least 5, then check if we've already seen this multiple of 5 before. If we have NOT seen this multiple of 5 before, then increment the bonus by 1. Now we can avoid double-counting.
if score>=5 and score%5==0:
for x in range(5,score+1,5):
score_array_mults_of_5 = []
score_array_mults_of_5.append(x)
for i in score_array_mults_of_5:
if (i in range(5,score-5,5))==False:
for _ in itertools.repeat(None, i):
bonus += 1
. . . except that this implementation also double counts and doesn't work either.
I've read StackExchange, the Python documentation, and I've tried my own solutions for two hours now. Please help.
EDIT: Thanks everyone. All helpful answers.
And for the person who asked what else affects the bonus: if the user presses a keyboard button, the bonus goes down by 1. I didn't mention that part because it seemed irrelevant.
Upvotes: 4
Views: 523
Reputation: 19264
You can just make bonus
score/5
:
>>> score = bonus = 0
>>> score+=5
>>> bonus = score/5
>>> bonus
1
>>> score+=5
>>> score+=5
>>> score+=5
>>> score+=5
>>> score
25
>>> bonus = score/5
>>> bonus
5
>>>
Here is a way of demonstrating that:
>>> while True:
... try:
... print 'Hit ^C to add 5 to score, and print score, bonus'
... time.sleep(1)
... except KeyboardInterrupt:
... score+=5
... bonus = score/5
... print score, bonus
...
Hit ^C to add 5 to score, and print score, bonus
Hit ^C to add 5 to score, and print score, bonus
^C5 1
Hit ^C to add 5 to score, and print score, bonus
Hit ^C to add 5 to score, and print score, bonus
^C10 2
Hit ^C to add 5 to score, and print score, bonus
^C15 3
Hit ^C to add 5 to score, and print score, bonus
^C20 4
Hit ^C to add 5 to score, and print score, bonus
^C25 5
Hit ^C to add 5 to score, and print score, bonus
^C30 6
Hit ^C to add 5 to score, and print score, bonus
^C35 7
Hit ^C to add 5 to score, and print score, bonus
Hit ^C to add 5 to score, and print score, bonus
...
To put this in your code, you would just have to put bonus = int(score/5)
after each time score
is added to.
Upvotes: 1
Reputation: 9075
Well, you could always simply do
bonus = int(score/5).
This will also ensure bonus goes down if score does (if that's possible, and the behavior you want)
But you could also use your first implementation as long as you only do the check when you've updated the score, rather than every game cycle.
Upvotes: 1