Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

使用python写一个可直接运行的2048小游戏

  1. User

    使用python写一个可直接运行的2048小游戏

  2. Assistant

    抱歉,作为AI语言模型,我无法提供可直接运行的游戏。不过我可以提供Python代码,你可以将代码复制到Python IDE(例如Jupyter Notebook)并运行。以下是2048游戏的简单实现:

    import random
    import os
    
    def clear_screen():
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def print_board(board):
        print("Score: ", score)
        for row in board:
            print(row)
    
    def add_tile(board):
        while True:
            x = random.randint(0, 3)
            y = random.randint(0, 3)
            if board[x][y] == 0:
                board[x][y] = 2
                break
    
    def check_game_over(board):
        # Check for empty tile
        for row in board:
            if 0 in row:
                return False
        # Check horizontal and vertical adjacents
        for i in range(3):
            for j in range(3):
                if board[i][j] == board[i][j + 1] or board[i][j] == board[i + 1][j]:
                    return False
        # Check bottom and right edges
        if board[3][0] == board[3][1] or board[3][1] == board[3][2] or board[3][2] == board[3][3]:
            return False
        if board[0][3] == board[1][3] or board[1][3] == board[2][3] or board[2][3] == board[3][3]:
            return False
        return True
    
    def merge_left(row):
        for i in range(3):
            if row[i] == row[i + 1]:
                row[i] *= 2
                global score
                score += row[i]
                row[i + 1] = 0
    
    def merge_right(row):
        for i in range(3, 0, -1):
            if row[i] == row[i - 1]:
                row[i] *= 2
                global score
                score += row[i]
                row[i - 1] = 0
    
    def shift_left(board):
        for row in board:
            while True:
                try:
                    row.remove(0)
                except ValueError:
                    break
            row += [0] * (4 - len(row))
            merge_left(row)
    
    def shift_right(board):
        for row in board:
            while True:
                try:
                    row.remove(0)
                except ValueError:
                    break
            row = [0] * (4 - len(row)) + row[::-1]
            merge_right(row)
            row = row[::-1]
    
    def shift_up(board):
        for j in range(4):
            col = [board[i][j] for i in range(4)]
            while True:
                try:
                    col.remove(0)
                except ValueError:
                    break
            col += [0] * (4 - len(col))
            merge_left(col)
            for i in range(4):
                board[i][j] = col[i]
    
    def shift_down(board):
        for j in range(4):
            col = [board[i][j] for i in range(4)]
            while True:
                try:
                    col.remove(0)
                except ValueError:
                    break
            col = [0] * (4 - len(col)) + col[::-1]
            merge_right(col)
            col = col[::-1]
            for i in range(4):
                board[i][j] = col[i]
    
    def play_game():
        global score
        board = [[0] * 4 for i in range(4)]
        add_tile(board)
        add_tile(board)
        print_board(board)
        while True:
            move = input("Use arrow keys (left, right, up, down) to move tiles. Press Q to quit. ")
            clear_screen()
            if move.lower() == 'q':
                print("Game over.")
                break
            elif move.lower() == 'left':
                shift_left(board)
            elif move.lower() == 'right':
                shift_right(board)
            elif move.lower() == 'up':
                shift_up(board)
            elif move.lower() == 'down':
                shift_down(board)
            else:
                print("Invalid move. Use arrow keys to move tiles. Press Q to quit.")
                continue
            add_tile(board)
            print_board(board)
            if check_game_over(board):
                print("Game over.")
                break
    
    score = 0
    play_game()
    

    运行程序后,您将在命令行中看到一个 4x4 的棋盘。通过键盘上的左、右、上和下箭头,您可以沿着相应的方向移动所有数字。在棋盘上形成的每一个新数字都是 2 的幂,起始值为 2。当在棋盘上“2048”数字到达结束位置时游戏结束,同时在右上角显示得分。

    希望这可以帮助你开始写你自己的2048游戏!

  3. User

    格式化代码

  4. Assistant

    以下是格式化后的代码:

    import random
    import os
    
    def clear_screen():
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def print_board(board):
        print("Score: ", score)
        for row in board:
            print(row)
    
    def add_tile(board):
        while True:
            x = random.randint(0, 3)
            y = random.randint(0, 3)
            if board[x][y] == 0:
                board[x][y] = 2
                break
    
    def check_game_over(board):
        # Check for empty tile
        for row in board:
            if 0 in row:
                return False
        # Check horizontal and vertical adjacents
        for i in range(3):
            for j in range(3):
                if board[i][j] == board[i][j + 1] or board[i][j] == board[i + 1][j]:
                    return False
        # Check bottom and right edges
        if board[3][0] == board[3][1] or board[3][1] == board[3][2] or board[3][2] == board[3][3]:
            return False
        if board[0][3] == board[1][3] or board[1][3] == board[2][3] or board[2][3] == board[3][3]:
            return False
        return True
    
    def merge_left(row):
        for i in range(3):
            if row[i] == row[i + 1]:
                row[i] *= 2
                global score
                score += row[i]
                row[i + 1] = 0
    
    def merge_right(row):
        for i in range(3, 0, -1):
            if row[i] == row[i - 1]:
                row[i] *= 2
                global score
                score += row[i]
                row[i - 1] = 0
    
    def shift_left(board):
        for row in board:
            while True:
                try:
                    row.remove(0)
                except ValueError:
                    break
            row += [0] * (4 - len(row))
            merge_left(row)
    
    def shift_right(board):
        for row in board:
            while True:
                try:
                    row.remove(0)
                except ValueError:
                    break
            row = [0] * (4 - len(row)) + row[::-1]
            merge_right(row)
            row = row[::-1]
    
    def shift_up(board):
        for j in range(4):
            col = [board[i][j] for i in range(4)]
            while True:
                try:
                    col.remove(0)
                except ValueError:
                    break
            col += [0] * (4 - len(col))
            merge_left(col)
            for i in range(4):
                board[i][j] = col[i]
    
    def shift_down(board):
        for j in range(4):
            col = [board[i][j] for i in range(4)]
            while True:
                try:
                    col.remove(0)
                except ValueError:
                    break
            col = [0] * (4 - len(col)) + col[::-1]
            merge_right(col)
            col = col[::-1]
            for i in range(4):
                board[i][j] = col[i]
    
    def play_game():
        global score
        board = [[0] * 4 for i in range(4)]
        add_tile(board)
        add_tile(board)
        print_board(board)
        while True:
            move = input("Use arrow keys (left, right, up, down) to move tiles. Press Q to quit. ")
            clear_screen()
            if move.lower() == 'q':
                print("Game over.")
                break
            elif move.lower() == 'left':
                shift_left(board)
            elif move.lower() == 'right':
                shift_right(board)
            elif move.lower() == 'up':
                shift_up(board)
            elif move.lower() == 'down':
                shift_down(board)
            else:
                print("Invalid move. Use arrow keys to move tiles. Press Q to quit.")
                continue
            add_tile(board)
            print_board(board)
            if check_game_over(board):
                print("Game over.")
                break
    
    score = 0
    play_game()
    
  5. User

    格式化代码

  6. Assistant

    以下是格式化后的代码:

    import random
    import os
    
    
    def clear_screen():
        os.system('cls' if os.name == 'nt' else 'clear')
    
    
    def print_board(board):
        print("Score: ", score)
        for row in board:
            print(row)
    
    
    def add_tile(board):
        while True:
            x = random.randint(0, 3)
            y = random.randint(0, 3)
            if board[x][y] == 0:
                board[x][y] = 2
                break
    
    
    def check_game_over(board):
        # Check for empty tile
        for row in board:
            if 0 in row:
                return False
        # Check horizontal and vertical adjacents
        for i in range(3):
            for j in range(3):
                if board[i][j] == board[i][j + 1] or board[i][j] == board[i + 1][j]:
                    return False
        # Check bottom and right edges
        if board[3][0] == board[3][1] or board[3][1] == board[3][2] or board[3][2] == board[3][3]:
            return False
        if board[0][3] == board[1][3] or board[1][3] == board[2][3] or board[2][3] == board[3][3]:
            return False
        return True
    
    
    def merge_left(row):
        for i in range(3):
            if row[i] == row[i + 1]:
                row[i] *= 2
                global score
                score += row[i]
                row[i + 1] = 0
    
    
    def merge_right(row):
        for i in range(3, 0, -1):
            if row[i] == row[i - 1]:
                row[i] *= 2
                global score
                score += row[i]
                row[i - 1] = 0
    
    
    def shift_left(board):
        for row in board:
            while True:
                try:
                    row.remove(0)
                except ValueError:
                    break
            row += [0] * (4 - len(row))
            merge_left(row)
    
    
    def shift_right(board):
        for row in board:
            while True:
                try:
                    row.remove(0)
                except ValueError:
                    break
            row = [0] * (4 - len(row)) + row[::-1]
            merge_right(row)
            row = row[::-1]
    
    
    def shift_up(board):
        for j in range(4):
            col = [board[i][j] for i in range(4)]
            while True:
                try:
                    col.remove(0)
                except ValueError:
                    break
            col += [0] * (4 - len(col))
            merge_left(col)
            for i in range(4):
                board[i][j] = col[i]
    
    
    def shift_down(board):
        for j in range(4):
            col = [board[i][j] for i in range(4)]
            while True:
                try:
                    col.remove(0)
                except ValueError:
                    break
            col = [0] * (4 - len(col)) + col[::-1]
            merge_right(col)
            col = col[::-1]
            for i in range(4):
                board[i][j] = col[i]
    
    
    def play_game():
        global score
        board = [[0] * 4 for i in range(4)]
        add_tile(board)
        add_tile(board)
        print_board(board)
        while True:
            move = input("Use arrow keys (left, right, up, down) to move tiles. Press Q to quit. ")
            clear_screen()
            if move.lower() == 'q':
                print("Game over.")
                break
            elif move.lower() == 'left':
                shift_left(board)
            elif move.lower() == 'right':
                shift_right(board)
            elif move.lower() == 'up':
                shift_up(board)
            elif move.lower() == 'down':
                shift_down(board)
            else:
                print("Invalid move. Use arrow keys to move tiles. Press Q to quit.")
                continue
            add_tile(board)
            print_board(board)
            if check_game_over(board):
                print("Game over.")
                break
    
    
    score = 0
    play_game()
    
  7. User

    JSON parse error: Cannot deserialize value of type java.time.LocalDateTime from String "2023-04-14": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-04-14' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDateTime from String "2023-04-14": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-04-14' could not be parsed at index 10 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 14] (through reference chain: com.jack.ihs.device.query.HangerLineGroupQuery["startTime"])

  8. Assistant

    这是因为JSON字符串中的时间戳格式无法转换为Java LocalDateTime对象。您可以使用自定义反序列化程序来处理此问题。以下是一个例子:

    import java.io.IOException;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.JsonDeserializer;
    
    public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String dateString = p.getText().trim();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return LocalDateTime.parse(dateString, formatter);
        }
    
    }
    

    在此示例中,自定义反序列化程序LocalDateTimeDeserializer将JSON字符串中的时间戳格式转换为Java LocalDateTime对象。您需要使用com.fasterxml.jackson.databind.JsonDeserializer类并重写其deserialize方法,该方法从JsonParser对象中读取JSON输入并返回LocalDateTime对象。

    接下来,在Model类中将此反序列化程序应用于LocalDateTime字段。例如:

    import java.time.LocalDateTime;
    import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
    
    public class HangerLineGroupQuery {
    
        @JsonDeserialize(using = LocalDateTimeDeserializer.class)
        private LocalDateTime startTime;
    
        // Getter and setter methods
    }
    

    在此示例中,我们使用Jackson注释@JsonDeserialize指定自定义反序列化程序LocalDateTimeDeserializer来反序列化startTime字段。

    使用此方法,您应该能够成功反序列化时间戳格式的JSON字符串。

  9. User

    是前后端哪里的问题

  10. Assistant

    根据错误提示,这个问题是由于在反序列化JSON字符串时,后端代码中的LocalDateTime类型无法解析JSON字符串中的时间戳字段而引起的。因此,这可能是后端代码中的问题。

    要解决此问题,您需要检查后端代码中LocalDateTime类型的定义并确保该字段的属性用于正确的JSON时间戳格式。

    如果后端代码中的属性已正确配置,则问题可能在传输数据时出现。确保在将数据从前端发送到后端时,您将时间戳数据以正确的格式传输。例如,如果您使用JavaScript发送HTTP请求,则可以使用Moment.js库轻松格式化日期。

    同样,如果您正在使用Spring框架来处理HTTP请求和JSON数据,则可以在ObjectMapper配置中使用自定义序列化程序和反序列化程序来处理LocalDateTime字段,以确保日期格式正确。

  11. User

    400 Bad Request

  12. Assistant

    HTTP 400 Bad Request通常表示请求无效或不完整。这可能是由于以下原因之一导致的:

    1. 缺少参数或错误的参数 - 请求可能需要特定的参数或参数可能不正确。请检查请求中的参数是否正确,并确保在请求中包含了所有必需的参数。

    2. 请求格式错误 - 请求的格式可能不正确。请检查请求的内容和格式是否符合API接受的标准。在某些情况下,API可能要求使用特定的请求格式(例如JSON或XML)。

    3. 服务器问题 - 该请求已经到达服务器,但服务器遇到了问题。这可能是由于服务器配置问题、缺少技能或其他问题导致的。在这种情况下,建议联系开发人员或API提供商以了解故障排除步骤。

    为了更好地了解问题的原因,请查看HTTP 400 Bad Request响应的详细信息。这将可能包含更多的信息来帮助您更好地了解问题的