首页 > 解决方案 > Python 3.7.1 Pygame 1.9.4 错误:TypeError:需要整数参数,得到浮点数

问题描述

所以,我正在构建一个非常简单的游戏。我打算跳一个圆圈。直到一切正常。但是当我尝试在游戏中添加跳转时,出现了一条错误消息,告诉我,“TypeError: integer argument expected, got float”我多次检查了代码。我似乎找不到错误。所以我在寻求帮助。这是我的代码:

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))

pygame.display.set_caption("A GAME")

screenWidth = 500

x = 100
y = 400
width = 50
height = 50
vel = 10
r = 15

isJump = False

jumpCount = 10

run = True

clock = pygame.time.Clock()

while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    clock.tick(60)

    keys = pygame.key.get_pressed()

    if keys [pygame.K_a] and x > r:
        x -= vel
    if keys [pygame.K_d] and x < screenWidth - r:
        x += vel
    if not (isJump):
        if keys [pygame.K_SPACE]:
            isJump = True
    else:
        if jumpCount >= -10:
            neg = 1
            if jumpCount < 0:
                neg = -1
            y -= (jumpCount ** 2) * 0.5 * neg
            jumpCount -= 1
        else:
            isJump = False
            jumpCount = 10
    if keys [pygame.K_ESCAPE]:
        run = False

    win.fill((0, 0, 0))


    pygame.draw.circle(win, (255, 0, 0), (x, y), r, 0)
    pygame.display.update()

pygame.quit()

请帮助

标签: pythonpygame

解决方案


这一行:

pygame.draw.circle(win, (255, 0, 0), (x, y), r, 0)

应改为:

pygame.draw.circle(win, (255, 0, 0), (x, int(y)), r, 0)

因为 y 在这一行之后是一个浮点数:

y -= (jumpCount ** 2) * 0.5 * neg

或者你可以像这样修复它:

y -= int((jumpCount ** 2) * 0.5 * neg)

Rudy 的回答会起作用,因为 floor Division(//) 的输出是一个 int:

y -= (jumpCount ** 2) // 2 * neg

推荐阅读