评估 python 问题分配中的函数

Evaluate function in python problem assignment

这里我在代码的第 68 行评估代码字符串时遇到问题"snake_y=snake_y-14" 我如何使用赋值评估字符串,因为我没有看到任何关于 eval() 函数中使用的赋值操作的问题

import pygame
import random
import time
import sys


def basic_defaults():
    pygame.init()
    snake_x = 200
    snake_y = 175
    font_for_game_title = pygame.font.Font(None, 36)
    screen = pygame.display.set_mode((800, 600)) #Making Screen for the game
    screen.blit(font_for_game_title.render("Snake Game", True, (0, 255, 255)), (300, 10))# Making title appear
    Clock = pygame.time.Clock()
    yolo=""
    return screen, snake_x, snake_y,Clock,yolo


def snake_movements():
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                yolo = "snake_y = snake_y - 14"
                return yolo
            elif event.key == pygame.K_DOWN:
                yolo = "snake_y = snake_y + 14"
                return yolo
            elif event.key == pygame.K_LEFT:
                yolo = "snake_x = snake_x - 14"
                return yolo
            elif event.key == pygame.K_RIGHT:
                yolo = "snake_x = snake_x + 14"
                return yolo
            else:
                #yolo = "snake_x += 14"
                #return yolo
                pass
def game_loop():
    screen, snake_x, snake_y,clocko,yolo = basic_defaults()
    running = True
    while (running):

        #for moving of snake in the game [code starts]
        screen.fill((0, 0, 0))
        '''for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    yolo="snake_y - 14"
                    return yolo
                elif event.key == pygame.K_DOWN:
                    yolo="snake_y + 14"
                    return yolo
                elif event.key == pygame.K_LEFT:
                    yolo="snake_x - 14"
                    return yolo
                elif event.key == pygame.K_RIGHT:
                    yolo="snake_x + 14"
                    return yolo
                else:
                    pass
                '''
        yolo=snake_movements()
        if yolo == None:
            pass
        else:
            #print(type(yolo))
            print(yolo)
            eval(yolo)
            #exec(yolo)
            print(snake_x, snake_y)
        pygame.draw.rect(screen, (102, 255, 51), (snake_x, snake_y, 10, 10), 4)
        pygame.display.update()
        #for moving of snake in the game [code ends]
        time.sleep(1)
        clocko.tick(30)

game_loop()

请尽快帮忙,因为我需要处理代码并需要完成此任务 提前致谢

一方面,我真的不明白为什么需要评估一个字符串,而不是直接执行该代码。最好不要使用 eval() 而只是使用代码。

不过,看起来你需要的是exec()函数。它类似于 eval(),但它允许 assignments/definitions。详细了解 exec()eval() here.

所以eval(yolo)应该改为exec(yolo)

也就是说,完全跳过使用 eval()exec() 会更干净、更高效。