Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

python - Why does 0 % 5 return 0?

I am making a game of pong right now, and I want the ball to speed up every 5 hits, but when I run the ball just starts speeding off in its starting direction.

It runs fine without the speeding up of the ball so the problem isn't previous code.

When trying to implement this I made a variable in my Ball class called self.num_hits and made it initially 0. Then in my game loop every time the ball collides, I increment the ball.num_hits and reverse its x_speed.

collide_list = pygame.sprite.spritecollide(ball, players, False)
if collide_list != []:
    ball.x_speed *= -1
    hit.play()
    ball.num_hits += 1

In the Ball() class:

if self.num_hits % 5 == 0:
        if self.x_speed > 0:
            self.x_speed += 2
        else:
            self.x_speed -= 2

But that made the ball speed off in its starting velocity, so I checked what self.num_hits % 5 was returning, and it always returns 0. I always thought that 0 % number = number, so my question is why does 0 % 5 return 0? And is there any other way I can make the ball speed up every 5 hits if I can't get around the 0 % 5 problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Division is defined so that the following is always true

n = q × d + r

where

  • n is the numerator (or dividend),
  • d != 0 is the denominator (or divisor),
  • q is the quotient, and
  • r > 0 is the remainder.

(This holds for positive and negative values; q is positive if n and d have the same sign and negative otherwise. r is defined to be always positive.)

In Python, n/d == q and n % d == r. If n is 0, then q must also be 0, in which case r must be 0 as well—all independent of the value of d.

(Off-topic, but note that this also captures the problem with division by 0: for non-zero d, q and r are uniquely determined; for d = 0, any value of q will satisfy the equation for r = n.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...