如何读取括号中包含坐标的用户输入

2024-10-01 17:30:38 发布

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

我正在做一个非常简单的游戏,你做一个数字表,并隐藏一个炸弹,用户需要找到。你知道吗

代码如下:

import random
def game(rows, colums):   
    table = (rows * colums - 1) * [' '] + ['bomb']    
    random.shuffle(table)    
    while True:    
        position = input('Enter next position (x, y):')    
        bombposition = position.split()    
        if table[int(bombposition[0])*colums + int(bombposition[1])] == 'bomb':    
            print('you found the bomb!')    
            break    
        else:    
            print('no bomb at', position) 

错误:

game(1,0)    
Enter next position (x, y):>?    
(1,0)    
Traceback (most recent call last):    
  File "input", line 1, in <module>   
  File "input", line 8, in game    
ValueError: invalid literal for int() with base 10: '(1,0)' 

Tags: gameinputlinetablepositionrandomfilerows
2条回答

您只需要更改计算bombposition的方式:

bombposition = position.lstrip("(").rstrip(")").split(",")

首先,默认情况下split使用空格,所以要在逗号上拆分,需要position.split(',')。尽管如此,如果继续拆分,您的split仍然会将()附加到字符串,例如在您的'(1''0)'中。我建议使用正则表达式从输入中提取数字

import re

position = input('Enter next position (x, y):') 
match = re.match(r'\((\d+)\, *(\d+)\)', position)
if match:
    x = int(match.group(1))
    y = int(match.group(2))
else:
    # input didn't match desired format of (x, y)

相关问题 更多 >

    热门问题