python和Op的帮助

2024-06-16 16:08:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python创建一个类似于battleship的程序(爱好者)。我尝试了一些东西,但我似乎不明白为什么即使条件匹配,这个程序也会返回miss。我错过了什么?谢谢

import random
import os
import time


XAXIS = [1,2,3,4,5,6,7,8,9,10]
YAXIS = [1,2,3,4,5,6,7,8,9,10]


########Generate Test Enemy Position
enemyPosX = random.randrange(1,len(XAXIS))
enemyPosY = random.randrange(1,len(YAXIS))


print(enemyPosX)
print(enemyPosY)





looping = True
while looping:
    xAim = input("set X gun position (1-10):: ")
    yAim = input("set Y gun position (1-10):: ")

    xAim = int(xAim)  #thought maybe I was comparing string to int
    yaim = int(yAim)

    print("{} {} :: {} {} ".format(enemyPosX, xAim, enemyPosY, yAim)) # Check Values for problem

    if (xAim == enemyPosX) and (yAim == enemyPosY): #<---- Should both return true but nope
        print("HIT!!!")
        time.sleep(3)
        looping = False
    else:
        print("MISS!!") #<--Getttin Miss regardless of Input
        ```

Tags: import程序lentimerandomintprintlooping
1条回答
网友
1楼 · 发布于 2024-06-16 16:08:17

下面这一行是你的问题

yaim = int(yAim)

注意资本化的差异。 因此,在if语句的条件下,您正在比较yAim(它仍然是一个字符串)和enemyPosY(它是一个整数),这将导致它成为False

if (xAim == enemyPosX) and (yAim == enemyPosY):

相关问题 更多 >