如何使随机数成为25的倍数

how to make a random number a multiple of 25

我正在开发一款贪吃蛇游戏,我希望苹果随机化其 x 和 y 坐标,但它与我的背景(20x20 网格)不对齐。

我试过取一个 0 到 20 之间的数字然后乘以 25,但是,最终它会随机消失。

有没有办法让随机整数成为预设数的倍数?

如果有帮助,这是我的代码:

# import library/libraries
import pygame as pg
import time
import random as r
pg.init ()

# creates the window
display = pg.display.set_mode ((500, 500))
pg.display.set_caption ("snake")

# snake
snake_x = 250
snake_y = 250
snake_x_change = 0
snake_y_change = 0
snake_x_size = 25
snake_y_size = 25
t = time.time ()

# apple
apple_x = 375
apple_y = 250
apple_x_size = 25
apple_y_size = 25

# definitions

def snake (x, y):
    pg.draw.rect (display, (0, 100, 0), pg.Rect (x, y, snake_x_size, snake_y_size))

def apple (x, y):
    pg.draw.rect (display, (100, 0, 0), pg.Rect (x, y, apple_x_size, apple_y_size))


# keeps the window open
execute = True
while execute:
    # sets window color (red, green, blue)
    display.fill ((0, 0, 0))
    # events
    for event in pg.event.get ():
        # checks if the X button has been pressed
        if event.type == pg.QUIT:
            execute = False
        # checks if a button is being held
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_w:
                snake_y_change = -25
                snake_x_change = 0
            if event.key == pg.K_a:
                snake_x_change = -25
                snake_y_change = 0
            if event.key == pg.K_s:
                snake_y_change = 25
                snake_x_change = 0
            if event.key == pg.K_d:
                snake_x_change = 25
                snake_y_change = 0
    # moves actors
    if time.time() > t + 0.1:
        t = time.time()
        snake_x = snake_x + snake_x_change
        snake_y = snake_y + snake_y_change
    # collision stuff
    if snake_x <= 0:
        snake_x = 0
    if snake_y <= 0:
        snake_y = 0
    if snake_x >= 475:
        snake_x = 475
    if snake_y >= 475:
        snake_y = 475
    if snake_x == apple_x and snake_y == apple_y:
        apple_x = r.randint (0, 20)
        apple_y = r.randint (0, 20)
        apple_x = apple_x * 25
        apple_y = apple_y * 25
    # loads actors
    snake (snake_x, snake_y)
    apple (apple_x, apple_y)
    # updates game window
    pg.display.flip ()

您可以四舍五入到最接近的 20 或 25。

apple_x = r.randint(0, round(475/20)*20)

不管是哪一个,你都让我很困惑。你说你想要25的倍数,但是网格是20x20.

要确保数字是 20 的倍数,您可以这样做:

apple_x = 20 * r.randint (0, 475)
apple_y = 20 * r.randint (0, 475)

注意您可以接受的最大数量并调整rand间隔。

我发现苹果为什么会消失了。 x/y 矩形或图像的坐标总是在右上角。

所以不是乘以 20,而是乘以 19。 对不起大家,抱歉给您造成了困扰。