我正在制作一个非常简单的游戏,您制作一张数字表并隐藏用户需要找到的炸弹

问题描述 投票:1回答:1

这里是代码:

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)' 
python random
1个回答
0
投票

首先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)
© www.soinside.com 2019 - 2024. All rights reserved.