使用indexerror创建if语句 - Python [英] Creating an if statement with a indexerror - Python

查看:487
本文介绍了使用indexerror创建if语句 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个类似于蛇的游戏。不同之处在于通过使用randint接收食物配给量,然后玩家将能够选择蛇应该在哪个方向上生长,起始位置也是随机选择的。游戏领域是用矩阵构建的,因此通过选择使列表超出范围的增长方向,可以进入墙壁。

I'm trying to create a game similar to snake. The difference is that a food ration is recieved by using randint and the player will then be able to choose in which direction the snake should grow, the starting position is also randomly chosen. The game field is built with a matrix and therefore it's possible to grow "into the walls" by chosing a growth direction that makes the list go out of range.

我的问题是,如果玩家选择以制作列表的方式成长,那么可以创建一个if状态来结束游戏游戏结束超出范围,例如:

My question is if it's possible to create an if statemant that would end the game with a "game over" if the player chose to grow in a way that makes the list go out of range, something like:

if IndexError: list index out of range : 
         print("Game over")

通过异常处理我的代码看起来像这样:

With the exception handling my code would look something like this:

 try :

    if p == 0:
        table[x][y] = "+"
    elif p == 1:
        table[x][y] = "+"
        table[x][y+1] = "+"
    elif p == 2:
        table[x][y] = "+"
        table[x][y+1] = "+"
        table[x][y+2] = "+"
    else:
        table[x][y] = "+"
        table[x][y+1] = "+"
        table[x][y+2] = "+"
        table[x][y+3] = "+"
 except IndexError :
                 print ("Game Over")

但我收到错误unindent do es不匹配任何outher缩进级别

But I'm getting the error "unindent does not match any outher indentation level"

推荐答案

使用异常处理

 try :
     #your code
 except IndexError:
    print "Game Over"

这篇关于使用indexerror创建if语句 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆