如何仅用两个键即左和右来控制蛇 [英] how to control snake with only two keys i.e left and right

查看:65
本文介绍了如何仅用两个键即左和右来控制蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用所有四个键来左右操纵蛇.我想知道如何只用左右键移动蛇.

currently, i'm using all four keys to steer the snake left, right, up and down. I'm wondering how can i only use left and right key to move the snake around.

                    if event.key == pygame.K_LEFT:
                        snake.direction = 2
                    elif event.key == pygame.K_RIGHT:
                        snake.direction = 3
                    elif event.key == pygame.K_UP:
                        snake.direction = 0
                    elif event.key == pygame.K_DOWN:
                        snake.direction = 1
    def move(self):
        if self.direction is 0:
            self.dy = -self.block
            self.dx = 0
        if self.direction is 1:
            self.dy = self.block
            self.dx = 0
        if self.direction is 2:
            self.dy = 0
            self.dx = -self.block
        if self.direction is 3:
            self.dy = 0
            self.dx = self.block
        self.x += self.dx
        self.y += self.dy

有人可以指导我该怎么做吗?

can anyone guide me how to do that?

推荐答案

定义方向如下:

  • 0:向上移动
  • 1:向右移动
  • 2:下移
  • 3:向右移动
def move(self):
    if self.direction is 0:
        self.dy = -self.block
        self.dx = 0
    if self.direction is 1:
        self.dy = 0
        self.dx = self.block
    if self.direction is 2:
        self.dy = 0
        self.dx = -self.block
    if self.direction is 3:
        self.dy = self.block
        self.dx = 0

    self.x += self.dx
    self.y += self.dy

当按 right 时,将1加到 snake.direction 上,当按 left 时,减去1.使用(模)运算符(请参见二进制算术运算)以确保结果在[0,3]范围内:

When right is pressed then add 1 to snake.direction and when left is pressed the subtract 1. Use the % (modulo) operator (see Binary arithmetic operations) to ensure tha the result is in rage [0, 3]:

if event.key == pygame.K_LEFT:
    snake.direction = (snake.direction - 1) % 4
if event.key == pygame.K_RIGHT:
    snake.direction = (snake.direction + 1) % 4

这篇关于如何仅用两个键即左和右来控制蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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