你如我软肋

文章 评论 浏览 30

你如我软肋 2025-02-13 19:17:29

您可以使用“名称”属性:

import cocotb
@cocotb.test()
async def my_wonderful_test(dut):
  print(my_wonderful_test.name);

但是不确定您想要的。

You can use "name" attribute :

import cocotb
@cocotb.test()
async def my_wonderful_test(dut):
  print(my_wonderful_test.name);

But not sure that exactly you want.

如何在COCOTB中获取当前的测试名称

你如我软肋 2025-02-13 12:03:56

我使用的解决方案是在 amplify.yaml 放大buildspec文件中创建事件。在每个步骤中,例如。后端:阶段,前端:阶段和测试阶段。

例如。

frontend:
    phases:
      preBuild:
        commands:
          - aws event put-events ....
      build:
        commands:
          - aws event put-events ....

然后,您实际上可以创建规则以匹配这些事件并发送到SNS,或者您的Telegram Webhooks可能是

The solution I used was to create event inside the amplify.yaml Amplify Buildspec file. on every steps eg. backend : phases , frontend: phases and test phases.

eg.

frontend:
    phases:
      preBuild:
        commands:
          - aws event put-events ....
      build:
        commands:
          - aws event put-events ....

Then you can actually create rule to match those events and sent to SNS or your Telegram webhooks may be

在AWS上获得构建和部署的状态

你如我软肋 2025-02-13 03:18:01

library(tidyr)

pivot_longer(df, -1, names_sep = "_", names_to = c(".value", "Year"))
#> # A tibble: 12 x 4
#>    Full.Name            Year    freq     Ra
#>    <chr>                <chr>  <dbl>  <dbl>
#>  1 A. Patrick Beharelle 2019   1.06   0.11 
#>  2 A. Patrick Beharelle 2020   1.43  -0.116
#>  3 Aaron P. Graft       2019  -1.5    0.276
#>  4 Aaron P. Graft       2020  -2.48   0.376
#>  5 Aaron P. Jagdfeld    2019  -2.42   0.745
#>  6 Aaron P. Jagdfeld    2020  21.8    0.889
#>  7 Adam H. Schechter    2019  -2.04   0.299
#>  8 Adam H. Schechter    2020  -0.47   0.296
#>  9 Adam P. Symson       2019   0.563  0.139
#> 10 Adam P. Symson       2020   1.05   0.292
#> 11 Adena T. Friedman    2019  -0.406  0.309
#> 12 Adena T. Friedman    2020  -0.11   0.242

reprex package (v2.0.1.1(v2.0.11 )

A slightly simpler solution would be

library(tidyr)

pivot_longer(df, -1, names_sep = "_", names_to = c(".value", "Year"))
#> # A tibble: 12 x 4
#>    Full.Name            Year    freq     Ra
#>    <chr>                <chr>  <dbl>  <dbl>
#>  1 A. Patrick Beharelle 2019   1.06   0.11 
#>  2 A. Patrick Beharelle 2020   1.43  -0.116
#>  3 Aaron P. Graft       2019  -1.5    0.276
#>  4 Aaron P. Graft       2020  -2.48   0.376
#>  5 Aaron P. Jagdfeld    2019  -2.42   0.745
#>  6 Aaron P. Jagdfeld    2020  21.8    0.889
#>  7 Adam H. Schechter    2019  -2.04   0.299
#>  8 Adam H. Schechter    2020  -0.47   0.296
#>  9 Adam P. Symson       2019   0.563  0.139
#> 10 Adam P. Symson       2020   1.05   0.292
#> 11 Adena T. Friedman    2019  -0.406  0.309
#> 12 Adena T. Friedman    2020  -0.11   0.242

Created on 2022-06-10 by the reprex package (v2.0.1)

R:将列转换为行数据集

你如我软肋 2025-02-12 03:27:27

这是基于 ymmx 的解决方案的解决方案

def twoSum(nums: List[int], target: int) -> List[int]:
    rest_dict = {}  # Dictionary to store A values.
    
    for index in range(len(nums)):  # Walk through in O(n) time
        value = nums[index]

        if value in rest_dict:  # Is value equal B to some previous A?
            return [index, rest_dict[value]]

        rest_dict[target - value] = index  # Store the wished B for value A

: >和 b 是整数,以便 a + b = target 。对于每个数字 a nums 中,保存 b target的其余部分-a )在字典 {REST:index} 。重复该过程,但现在检查词典中的下一个值 a'是否。这意味着,检查 a'= b 是否。如果是真的,请返回其索引。

Here is a solution based on the solution of ymmx but improved:

def twoSum(nums: List[int], target: int) -> List[int]:
    rest_dict = {}  # Dictionary to store A values.
    
    for index in range(len(nums)):  # Walk through in O(n) time
        value = nums[index]

        if value in rest_dict:  # Is value equal B to some previous A?
            return [index, rest_dict[value]]

        rest_dict[target - value] = index  # Store the wished B for value A

The idea here is: let A and B be integers such that A + B = target. For each number A in nums, save the B (rest of target - A) in a dictionary {rest: index}. Repeat the procedure but now check if the next value A' is in the dictionary. It means, check if A' = B. If true, return their indexes.

如何在O(n)时间复杂性中与包括负整数的阵列解决两个总和

你如我软肋 2025-02-12 00:24:02

您将需要查看:

因此,您的基本问题是一个“简单”的三角学问题(我说简单,但我是个白痴)。您有两个点的空间,需要计算它们之间的角度,例如...

 // Radians
 -Math.atan2(startY - endY, startX - endX)

可运行的示例...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GamePanel gamePanel = new GamePanel();
                JFrame frame = new JFrame();
                frame.add(gamePanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                gamePanel.startGameThread();
            }
        });
    }

    public class GamePanel extends JPanel { //implements Runnable {

        // SCREEN SETTINGS
        final int originalTitleSize = 16; // 16x16 title
        final int scale = 3; //16x3(scale) = 48

        public final int tileSize = originalTitleSize * scale; //48x48 title
        final int maxScreenCol = 16;
        final int maxScreenRow = 12;
        final int screenWidth = tileSize * maxScreenCol; // 768 pixels
        final int screenHeight = tileSize * maxScreenRow; // 576 pixels

        //FPS
        int FPS = 60;

        Player player = new Player(this);

        private Timer timer;
        private Set<KeyAction.Direction> movementState = new HashSet<>();
        private Point lastKnownMousePoint;

        public GamePanel() {
            this.setBackground(Color.BLACK);

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    lastKnownMousePoint = e.getPoint();
                }
            });

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "Pressed.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "Released.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "Pressed.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "Released.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "Pressed.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "Released.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "Pressed.right");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "Released.right");

            ActionMap am = getActionMap();

            am.put("Pressed.up", new KeyAction(KeyAction.Direction.UP, true, movementState));
            am.put("Released.up", new KeyAction(KeyAction.Direction.UP, false, movementState));
            am.put("Pressed.down", new KeyAction(KeyAction.Direction.DOWN, true, movementState));
            am.put("Released.down", new KeyAction(KeyAction.Direction.DOWN, false, movementState));
            am.put("Pressed.left", new KeyAction(KeyAction.Direction.LEFT, true, movementState));
            am.put("Released.left", new KeyAction(KeyAction.Direction.LEFT, false, movementState));
            am.put("Pressed.right", new KeyAction(KeyAction.Direction.RIGHT, true, movementState));
            am.put("Released.right", new KeyAction(KeyAction.Direction.RIGHT, false, movementState));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(screenWidth, screenHeight);
        }

        public void startGameThread() {
            if (timer == null) {
                timer = new Timer((int) Math.floor(1000f / FPS), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        update();
                        repaint();
                    }
                });
            }
            timer.start();
        }

        public void update() {
            if (movementState.contains(KeyAction.Direction.UP)) {
                player.y -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.DOWN)) {
                player.y += player.speed;
            } else if (movementState.contains(KeyAction.Direction.LEFT)) {
                player.x -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.RIGHT)) {
                player.x += player.speed;
            }

            if (lastKnownMousePoint != null) {
                // This assumes that character is facing "UP" by default
                // That is, 0 has the character entity facing towards to the
                // top of the sceen.  If the character is facing in a different
                // direction, then you will need to offset this calculation
                // to compenstate, but that might be better done in the player
                // entity
                double angle = -Math.toDegrees(Math.atan2(player.x - lastKnownMousePoint.x, player.y - lastKnownMousePoint.y));
                player.angleInDegrees = angle;
            }
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            player.draw(g2);
            g2.dispose();
        }

    }

    public class KeyAction extends AbstractAction {
        enum Direction {
            UP, DOWN, LEFT, RIGHT
        }

        private Direction direction;
        private boolean activate;
        private Set<Direction> inputState;

        public KeyAction(Direction direction, boolean activate, Set<Direction> inputState) {
            this.direction = direction;
            this.activate = activate;
            this.inputState = inputState;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (activate) {
                inputState.add(direction);
            } else {
                inputState.remove(direction);
            }
        }
    }

    public class Entity {
        public int x;
        public int y;
        public int speed;
    }

    public class Player extends Entity {

        GamePanel gp;

        double angleInDegrees = 0;

        public Player(GamePanel gp) {
            this.gp = gp;
            setDefaultValues();
        }

        public void setDefaultValues() {
            x = 100;
            y = 100;
            speed = 4;
        }

        public void draw(Graphics2D g2) {
            g2 = (Graphics2D) g2.create();
            g2.translate(x, y);
            g2.rotate(Math.toRadians(angleInDegrees), (gp.tileSize / 2), (gp.tileSize / 2));
            g2.setColor(Color.yellow);
            g2.fillRect(0, 0, gp.tileSize, gp.tileSize);
            g2.setColor(Color.RED);
            g2.drawLine((gp.tileSize / 2), (gp.tileSize / 2), (gp.tileSize / 2), 0);
            g2.dispose();
        }
    }
}

哦,旋转点在玩家中间(矩形)的旋转点也不正确。有些不需要准确,我真的做

只是当心,您可能永远不会找到解决问题的“确切”解决方案,而您需要花时间进行实验;)

好的,这似乎是有效的对我来说,直到我开始调试它。问题是,原始代码是从鼠标点和当前X/y点的角度计算的角度。它应该使用玩家“旋转”点,在此示例中,这是播放器中点。

因此,我添加了...

public Point midPoint() {
    return new Point(x + (gp.tileSize / 2), y + (gp.tileSize / 2));
}

player ,因此我们可以轻松地获取玩家的中点(并且不必重新输入它),

然后我更新了角度计算以利用它,例如..

Point playerMidPoint = player.midPoint();
double angle = Math.toDegrees(Math.atan2(lastKnownMousePoint.y - playerMidPoint.y, lastKnownMousePoint.x - playerMidPoint.x)) + 90d;
player.angleInDegrees = angle;

可运行的示例...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GamePanel gamePanel = new GamePanel();
                JFrame frame = new JFrame();
                frame.add(gamePanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                gamePanel.startGameThread();
            }
        });
    }

    public class GamePanel extends JPanel { //implements Runnable {

        // SCREEN SETTINGS
        final int originalTitleSize = 16; // 16x16 title
        final int scale = 3; //16x3(scale) = 48

        public final int tileSize = originalTitleSize * scale; //48x48 title
        final int maxScreenCol = 16;
        final int maxScreenRow = 12;
        final int screenWidth = tileSize * maxScreenCol; // 768 pixels
        final int screenHeight = tileSize * maxScreenRow; // 576 pixels

        //FPS
        int FPS = 60;

        Player player = new Player(this);

        private Timer timer;
        private Set<KeyAction.Direction> movementState = new HashSet<>();
        private Point lastKnownMousePoint;

        public GamePanel() {
            this.setBackground(Color.BLACK);

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    lastKnownMousePoint = new Point(e.getPoint());
                }
            });

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "Pressed.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "Released.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "Pressed.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "Released.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "Pressed.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "Released.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "Pressed.right");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "Released.right");

            ActionMap am = getActionMap();

            am.put("Pressed.up", new KeyAction(KeyAction.Direction.UP, true, movementState));
            am.put("Released.up", new KeyAction(KeyAction.Direction.UP, false, movementState));
            am.put("Pressed.down", new KeyAction(KeyAction.Direction.DOWN, true, movementState));
            am.put("Released.down", new KeyAction(KeyAction.Direction.DOWN, false, movementState));
            am.put("Pressed.left", new KeyAction(KeyAction.Direction.LEFT, true, movementState));
            am.put("Released.left", new KeyAction(KeyAction.Direction.LEFT, false, movementState));
            am.put("Pressed.right", new KeyAction(KeyAction.Direction.RIGHT, true, movementState));
            am.put("Released.right", new KeyAction(KeyAction.Direction.RIGHT, false, movementState));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(screenWidth, screenHeight);
        }

        public void startGameThread() {
            if (timer == null) {
                timer = new Timer((int) Math.floor(1000f / FPS), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        update();
                        repaint();
                    }
                });
            }
            timer.start();
        }

        public void update() {
            if (movementState.contains(KeyAction.Direction.UP)) {
                player.y -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.DOWN)) {
                player.y += player.speed;
            } else if (movementState.contains(KeyAction.Direction.LEFT)) {
                player.x -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.RIGHT)) {
                player.x += player.speed;
            }

            if (lastKnownMousePoint != null) {
                // This assumes that character is facing "UP" by default
                // That is, 0 has the character entity facing towards to the
                // top of the sceen.  If the character is facing in a different
                // direction, then you will need to offset this calculation
                // to compenstate, but that might be better done in the player
                // entity
                Point playerMidPoint = player.midPoint();
                double angle = Math.toDegrees(Math.atan2(lastKnownMousePoint.y - playerMidPoint.y, lastKnownMousePoint.x - playerMidPoint.x)) + 90d;
                player.angleInDegrees = angle;
                repaint();
            }
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            player.draw(g2);
            g2.dispose();
            if (lastKnownMousePoint != null) {
                g2 = (Graphics2D) g;
                g2.setColor(Color.GREEN);

                int midX = player.x + (tileSize / 2);
                int midY = player.y + (tileSize / 2);
                g2.drawLine(midX, midY, lastKnownMousePoint.x, lastKnownMousePoint.y);
                g2.dispose();
            }
        }

    }

    public class KeyAction extends AbstractAction {
        enum Direction {
            UP, DOWN, LEFT, RIGHT
        }

        private Direction direction;
        private boolean activate;
        private Set<Direction> inputState;

        public KeyAction(Direction direction, boolean activate, Set<Direction> inputState) {
            this.direction = direction;
            this.activate = activate;
            this.inputState = inputState;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (activate) {
                inputState.add(direction);
            } else {
                inputState.remove(direction);
            }
        }
    }

    public class Entity {
        public int x;
        public int y;
        public int speed;
    }

    public class Player extends Entity {

        GamePanel gp;

        double angleInDegrees = 0;

        public Player(GamePanel gp) {
            this.gp = gp;
            setDefaultValues();
        }

        public void setDefaultValues() {
            x = 100;
            y = 100;
            speed = 4;
        }

        public Point midPoint() {
            return new Point(x + (gp.tileSize / 2), y + (gp.tileSize / 2));
        }

        public void draw(Graphics2D g2) {
            g2 = (Graphics2D) g2.create();
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.toRadians(angleInDegrees), (gp.tileSize / 2d), (gp.tileSize / 2d));
            g2.transform(at);
            g2.setColor(Color.yellow);
            g2.fillRect(0, 0, gp.tileSize, gp.tileSize);
            g2.setColor(Color.RED);
            g2.drawLine((gp.tileSize / 2), (gp.tileSize / 2), (gp.tileSize / 2), 0);
            g2.dispose();
        }
    }
}

You will want to have a look at:

  • Key bindings - these will solve all the focus related issues with KeyListener
  • Concurrency in Swing and probably switch over to using a Swing Timer. Swing is NOT thread safe, it's not a good idea to use Thread as your "main loop".

So your basic problem is a "simple" trigonometry problem (I as say simple, but I'm an idiot). You have two points in space and need to calculate the angle between them, for example...

 // Radians
 -Math.atan2(startY - endY, startX - endX)

Runnable example...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GamePanel gamePanel = new GamePanel();
                JFrame frame = new JFrame();
                frame.add(gamePanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                gamePanel.startGameThread();
            }
        });
    }

    public class GamePanel extends JPanel { //implements Runnable {

        // SCREEN SETTINGS
        final int originalTitleSize = 16; // 16x16 title
        final int scale = 3; //16x3(scale) = 48

        public final int tileSize = originalTitleSize * scale; //48x48 title
        final int maxScreenCol = 16;
        final int maxScreenRow = 12;
        final int screenWidth = tileSize * maxScreenCol; // 768 pixels
        final int screenHeight = tileSize * maxScreenRow; // 576 pixels

        //FPS
        int FPS = 60;

        Player player = new Player(this);

        private Timer timer;
        private Set<KeyAction.Direction> movementState = new HashSet<>();
        private Point lastKnownMousePoint;

        public GamePanel() {
            this.setBackground(Color.BLACK);

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    lastKnownMousePoint = e.getPoint();
                }
            });

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "Pressed.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "Released.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "Pressed.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "Released.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "Pressed.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "Released.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "Pressed.right");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "Released.right");

            ActionMap am = getActionMap();

            am.put("Pressed.up", new KeyAction(KeyAction.Direction.UP, true, movementState));
            am.put("Released.up", new KeyAction(KeyAction.Direction.UP, false, movementState));
            am.put("Pressed.down", new KeyAction(KeyAction.Direction.DOWN, true, movementState));
            am.put("Released.down", new KeyAction(KeyAction.Direction.DOWN, false, movementState));
            am.put("Pressed.left", new KeyAction(KeyAction.Direction.LEFT, true, movementState));
            am.put("Released.left", new KeyAction(KeyAction.Direction.LEFT, false, movementState));
            am.put("Pressed.right", new KeyAction(KeyAction.Direction.RIGHT, true, movementState));
            am.put("Released.right", new KeyAction(KeyAction.Direction.RIGHT, false, movementState));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(screenWidth, screenHeight);
        }

        public void startGameThread() {
            if (timer == null) {
                timer = new Timer((int) Math.floor(1000f / FPS), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        update();
                        repaint();
                    }
                });
            }
            timer.start();
        }

        public void update() {
            if (movementState.contains(KeyAction.Direction.UP)) {
                player.y -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.DOWN)) {
                player.y += player.speed;
            } else if (movementState.contains(KeyAction.Direction.LEFT)) {
                player.x -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.RIGHT)) {
                player.x += player.speed;
            }

            if (lastKnownMousePoint != null) {
                // This assumes that character is facing "UP" by default
                // That is, 0 has the character entity facing towards to the
                // top of the sceen.  If the character is facing in a different
                // direction, then you will need to offset this calculation
                // to compenstate, but that might be better done in the player
                // entity
                double angle = -Math.toDegrees(Math.atan2(player.x - lastKnownMousePoint.x, player.y - lastKnownMousePoint.y));
                player.angleInDegrees = angle;
            }
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            player.draw(g2);
            g2.dispose();
        }

    }

    public class KeyAction extends AbstractAction {
        enum Direction {
            UP, DOWN, LEFT, RIGHT
        }

        private Direction direction;
        private boolean activate;
        private Set<Direction> inputState;

        public KeyAction(Direction direction, boolean activate, Set<Direction> inputState) {
            this.direction = direction;
            this.activate = activate;
            this.inputState = inputState;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (activate) {
                inputState.add(direction);
            } else {
                inputState.remove(direction);
            }
        }
    }

    public class Entity {
        public int x;
        public int y;
        public int speed;
    }

    public class Player extends Entity {

        GamePanel gp;

        double angleInDegrees = 0;

        public Player(GamePanel gp) {
            this.gp = gp;
            setDefaultValues();
        }

        public void setDefaultValues() {
            x = 100;
            y = 100;
            speed = 4;
        }

        public void draw(Graphics2D g2) {
            g2 = (Graphics2D) g2.create();
            g2.translate(x, y);
            g2.rotate(Math.toRadians(angleInDegrees), (gp.tileSize / 2), (gp.tileSize / 2));
            g2.setColor(Color.yellow);
            g2.fillRect(0, 0, gp.tileSize, gp.tileSize);
            g2.setColor(Color.RED);
            g2.drawLine((gp.tileSize / 2), (gp.tileSize / 2), (gp.tileSize / 2), 0);
            g2.dispose();
        }
    }
}

Oh, and also the rotation point is not right in the middle of the player (rectangle). Some dont need accurancy, I really do

Just beware, you're probably never going to find the "exact" solutions to your problems and you're going to need to take the time to experiment ;)

Okay, admittedly, that seemed to work for me, until I started debugging it. The problem was, the original code was calculating the angle from the mouse point and the players current x/y point. It should be using the players "rotation" point, which, in this example, is the players mid point.

So, I added...

public Point midPoint() {
    return new Point(x + (gp.tileSize / 2), y + (gp.tileSize / 2));
}

to Player, so we can easily get the player's mid point (and not have to retype that a lot)

I then updated the angle calculation to make use of it, for example..

Point playerMidPoint = player.midPoint();
double angle = Math.toDegrees(Math.atan2(lastKnownMousePoint.y - playerMidPoint.y, lastKnownMousePoint.x - playerMidPoint.x)) + 90d;
player.angleInDegrees = angle;

enter image description here

Runnable example...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GamePanel gamePanel = new GamePanel();
                JFrame frame = new JFrame();
                frame.add(gamePanel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                gamePanel.startGameThread();
            }
        });
    }

    public class GamePanel extends JPanel { //implements Runnable {

        // SCREEN SETTINGS
        final int originalTitleSize = 16; // 16x16 title
        final int scale = 3; //16x3(scale) = 48

        public final int tileSize = originalTitleSize * scale; //48x48 title
        final int maxScreenCol = 16;
        final int maxScreenRow = 12;
        final int screenWidth = tileSize * maxScreenCol; // 768 pixels
        final int screenHeight = tileSize * maxScreenRow; // 576 pixels

        //FPS
        int FPS = 60;

        Player player = new Player(this);

        private Timer timer;
        private Set<KeyAction.Direction> movementState = new HashSet<>();
        private Point lastKnownMousePoint;

        public GamePanel() {
            this.setBackground(Color.BLACK);

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    lastKnownMousePoint = new Point(e.getPoint());
                }
            });

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "Pressed.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "Released.up");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "Pressed.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "Released.down");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "Pressed.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "Released.left");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "Pressed.right");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "Released.right");

            ActionMap am = getActionMap();

            am.put("Pressed.up", new KeyAction(KeyAction.Direction.UP, true, movementState));
            am.put("Released.up", new KeyAction(KeyAction.Direction.UP, false, movementState));
            am.put("Pressed.down", new KeyAction(KeyAction.Direction.DOWN, true, movementState));
            am.put("Released.down", new KeyAction(KeyAction.Direction.DOWN, false, movementState));
            am.put("Pressed.left", new KeyAction(KeyAction.Direction.LEFT, true, movementState));
            am.put("Released.left", new KeyAction(KeyAction.Direction.LEFT, false, movementState));
            am.put("Pressed.right", new KeyAction(KeyAction.Direction.RIGHT, true, movementState));
            am.put("Released.right", new KeyAction(KeyAction.Direction.RIGHT, false, movementState));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(screenWidth, screenHeight);
        }

        public void startGameThread() {
            if (timer == null) {
                timer = new Timer((int) Math.floor(1000f / FPS), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        update();
                        repaint();
                    }
                });
            }
            timer.start();
        }

        public void update() {
            if (movementState.contains(KeyAction.Direction.UP)) {
                player.y -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.DOWN)) {
                player.y += player.speed;
            } else if (movementState.contains(KeyAction.Direction.LEFT)) {
                player.x -= player.speed;
            } else if (movementState.contains(KeyAction.Direction.RIGHT)) {
                player.x += player.speed;
            }

            if (lastKnownMousePoint != null) {
                // This assumes that character is facing "UP" by default
                // That is, 0 has the character entity facing towards to the
                // top of the sceen.  If the character is facing in a different
                // direction, then you will need to offset this calculation
                // to compenstate, but that might be better done in the player
                // entity
                Point playerMidPoint = player.midPoint();
                double angle = Math.toDegrees(Math.atan2(lastKnownMousePoint.y - playerMidPoint.y, lastKnownMousePoint.x - playerMidPoint.x)) + 90d;
                player.angleInDegrees = angle;
                repaint();
            }
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            player.draw(g2);
            g2.dispose();
            if (lastKnownMousePoint != null) {
                g2 = (Graphics2D) g;
                g2.setColor(Color.GREEN);

                int midX = player.x + (tileSize / 2);
                int midY = player.y + (tileSize / 2);
                g2.drawLine(midX, midY, lastKnownMousePoint.x, lastKnownMousePoint.y);
                g2.dispose();
            }
        }

    }

    public class KeyAction extends AbstractAction {
        enum Direction {
            UP, DOWN, LEFT, RIGHT
        }

        private Direction direction;
        private boolean activate;
        private Set<Direction> inputState;

        public KeyAction(Direction direction, boolean activate, Set<Direction> inputState) {
            this.direction = direction;
            this.activate = activate;
            this.inputState = inputState;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (activate) {
                inputState.add(direction);
            } else {
                inputState.remove(direction);
            }
        }
    }

    public class Entity {
        public int x;
        public int y;
        public int speed;
    }

    public class Player extends Entity {

        GamePanel gp;

        double angleInDegrees = 0;

        public Player(GamePanel gp) {
            this.gp = gp;
            setDefaultValues();
        }

        public void setDefaultValues() {
            x = 100;
            y = 100;
            speed = 4;
        }

        public Point midPoint() {
            return new Point(x + (gp.tileSize / 2), y + (gp.tileSize / 2));
        }

        public void draw(Graphics2D g2) {
            g2 = (Graphics2D) g2.create();
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.toRadians(angleInDegrees), (gp.tileSize / 2d), (gp.tileSize / 2d));
            g2.transform(at);
            g2.setColor(Color.yellow);
            g2.fillRect(0, 0, gp.tileSize, gp.tileSize);
            g2.setColor(Color.RED);
            g2.drawLine((gp.tileSize / 2), (gp.tileSize / 2), (gp.tileSize / 2), 0);
            g2.dispose();
        }
    }
}

您如何制作,您的玩家在Java2d上自上而下的游戏始终向鼠标看

你如我软肋 2025-02-11 18:35:18

也许以下CRTP变体足以使用您:

template<typename Arg> class Abase
{
  friend Arg;
  virtual int foo(int) = 0; // this is the private interface you want to access
public:
  virtual ~Abase() {}
};

template<typename... Args> class A:
  public Abase<Args> ...
{
  virtual int foo(int arg) { return frobnicate(arg); }
  // ...
}

然后,您通过的每个类都可以通过相应的 abase base类访问该私人界面,例如

class X
{
public:
  // assumes X is in the Args
  template<typename Args ...> int foo(A<Args...>* p)
  {
    Abase<X>* pX = p; // will fail if X is not in Args
    return pX->foo(3); // works because X is friend of Abase<X>
  }
};

Maybe the following CRTP variant would be sufficient for your use:

template<typename Arg> class Abase
{
  friend Arg;
  virtual int foo(int) = 0; // this is the private interface you want to access
public:
  virtual ~Abase() {}
};

template<typename... Args> class A:
  public Abase<Args> ...
{
  virtual int foo(int arg) { return frobnicate(arg); }
  // ...
}

Then each class you pass in Args can access that private interface through the corresponding Abase base class, for example

class X
{
public:
  // assumes X is in the Args
  template<typename Args ...> int foo(A<Args...>* p)
  {
    Abase<X>* pX = p; // will fail if X is not in Args
    return pX->foo(3); // works because X is friend of Abase<X>
  }
};

使用variadic模板指定朋友类

你如我软肋 2025-02-11 14:41:50

安装在环境上的PHP版本应与您的项目兼容。

如果您的项目基于Composer软件包管理器(如我所见),则可以帮助您控制服务器上需要的PHP版本。

在您的情况下,我建议从快照恢复,或者只安装PHP 7.1.3版本。

如果您想在项目中使用PHP 7.4/8/8.1,则在升级代码和项目依赖项之前,请确保所有内容都可以使用所需版本的PHP。

The php version installed on your environment should be compatible with your project.

If your project is based on composer package manager (as I see), it can help you to control which php version you need on the server.

In your case I would recommend to restore from the snapshot or just install php 7.1.3 version back.

If you want to use php 7.4/8/8.1 in your project, before you should upgrade your code and project dependencies and ensure, that everything working fine with the desired version of php.

如何降级PHP版本(您的PHP版本不满足该要求)?

你如我软肋 2025-02-10 22:17:59

没有办法优先考虑特定消息。我认为正确的方法是创建一个单独的主题。

There is no way to prioritize particular messages. I think the right way is to create a separate topic.

GCP酒吧/次优先级队列

你如我软肋 2025-02-10 20:53:10

这就是我解决问题的方式

class myClass
{
    constructor(parent)
    {
        this.callback = (function() { 
            this.callbackFunctionOfParent();             
        }).bind(parent);
    }

    callCallback() {
         this.callback();
    }
}

class Class2
{
       constructor()
       {
            this.Name = "CLASS 2";

            this.test = new myClass(this);

            this.test.callCallback();
       } 

       callbackFunctionOfParent()
       {
           console.log("parent is: " + this.Name);
       }
}

var c2 = new Class2;

This is how I solved the problem

class myClass
{
    constructor(parent)
    {
        this.callback = (function() { 
            this.callbackFunctionOfParent();             
        }).bind(parent);
    }

    callCallback() {
         this.callback();
    }
}

class Class2
{
       constructor()
       {
            this.Name = "CLASS 2";

            this.test = new myClass(this);

            this.test.callCallback();
       } 

       callbackFunctionOfParent()
       {
           console.log("parent is: " + this.Name);
       }
}

var c2 = new Class2;

如何在回调中访问正确的`

你如我软肋 2025-02-10 20:29:24

问题是包装 strsplit(。) in c(。)不会改变它仍然是 list 唯一的将在列表级别上运行,而不是单词级别。

c(strsplit(rep(a, 2), "\\s+"))
# [[1]]
# [1] "an"    "apple" "is"    "an"    "apple"
# [[2]]
# [1] "an"    "apple" "is"    "an"    "apple"
unique(c(strsplit(rep(a, 2), "\\s+")))
# [[1]]
# [1] "an"    "apple" "is"    "an"    "apple"

替代方案:

  1. 如果长度(a)总是1,那么

      unique(strsplit(a,“ \\ s+”)[[1])
    #[1]“ a”“苹果”是”   
     
  2. 如果长度(a)可以是2个或更多,您想要唯一单词的列表每个句子,然后

      a2&lt;  -  c(“苹果是苹果”,“梨是梨”,“橙色是橙色”)
    lapply(strsplit(a2,“ \\ s+”),唯一)
    #[[1]]
    #[1]“ a”“苹果”是”   
    #[[2]]
    #[1]“ a”“”梨“是”  
    #[[3]]
    #[1]“ an”“橙色”“是”    
     

    (注意:这总是返回 list ,无论输入中的句子数量如何。)

  3. 如果长度(a)可以是2个ore,并且您希望在所有句子中使用唯一的单词 ,然后


    #[1]“ a”“苹果”是“”一个“”“梨”“橙色”

    (注意:当长度(a)为1时,此方法也很好地工作。)

The problem is that wrapping strsplit(.) in c(.) does not change the fact that it is still a list, and unique will be operating at the list-level, not the word-level.

c(strsplit(rep(a, 2), "\\s+"))
# [[1]]
# [1] "an"    "apple" "is"    "an"    "apple"
# [[2]]
# [1] "an"    "apple" "is"    "an"    "apple"
unique(c(strsplit(rep(a, 2), "\\s+")))
# [[1]]
# [1] "an"    "apple" "is"    "an"    "apple"

Alternatives:

  1. If length(a) is always 1, then perhaps

    unique(strsplit(a, "\\s+")[[1]])
    # [1] "an"    "apple" "is"   
    
  2. If length(a) can be 2 or more and you want a list of unique words for each sentence, then

    a2 <- c("an apple is an apple", "a pear is a pear", "an orange is an orange")
    lapply(strsplit(a2, "\\s+"), unique)
    # [[1]]
    # [1] "an"    "apple" "is"   
    # [[2]]
    # [1] "a"    "pear" "is"  
    # [[3]]
    # [1] "an"     "orange" "is"    
    

    (Note: this always returns a list, regardless of the number of sentences in the input.)

  3. if length(a) can be 2 ore more and you want a unique words across all sentences, then

    unique(unlist(strsplit(a2, "\\s+")))
    # [1] "an"     "apple"  "is"     "a"      "pear"   "orange"
    

    (Note: this method also works well when length(a) is 1.)

仅返回独特的单词

你如我软肋 2025-02-10 19:16:07

https://patorjk.com/software/taag/

大多数如果不是全部的Figlet Fonts都在此处存储

https://patorjk.com/software/taag/

Most if not all figlet fonts are stored here

更多的figlet文字

你如我软肋 2025-02-10 02:40:08

this syntax:

import '@interactjs/auto-start'
import '@interactjs/actions/drag'
import '@interactjs/actions/resize'
import '@interactjs/modifiers'
import '@interactjs/dev-tools'
import interact from '@interactjs/interact'

is used for npm modules import.如果不预处理代码,就无法在浏览器中执行此操作。您可以像这样导入库,最好是在单独的脚本标签中。 But if you plan to import only one library you can set it

<script src="CDN url"></script>

Put it above your other script tag.找到适合您库的CDN主机。示例: https://cdnjs.com/librararies/librararies/interact.js/1.0.0.0.0.0.0.2 < /a>

You can't use those import statements like this.如果您从CDN导入库,则可以像文档中一样使用它。查看 https://interactjs.io/docs/installation cdn cdn cdn pre-bund-pre-bundundled用法。我认为 Interact 是全局曝光的,您不必导入任何东西。

如果您想以适当的方式了解这一点,则将为您的前端应用程序设置一个单独的项目/文件夹。然后必须构建该应用程序,然后您将构建的分发文件附加在Rails HTML中。这取决于您的目的。

this syntax:

import '@interactjs/auto-start'
import '@interactjs/actions/drag'
import '@interactjs/actions/resize'
import '@interactjs/modifiers'
import '@interactjs/dev-tools'
import interact from '@interactjs/interact'

is used for npm modules import. You can't do that in the browser without preprocessing your code. You can import the library like this, preferably in a separate script tag. But if you plan to import only one library you can set it

<script src="CDN url"></script>

Put it above your other script tag. Find an appropriate CDN host for your library. Example: https://cdnjs.com/libraries/interact.js/1.0.2

You can't use those import statements like this. If you import the library from CDN, you can use it like in the documentation. Look at https://interactjs.io/docs/installation CDN pre-bundled usage. I presume interact is globally exposed and you don't have to import anything.

If you want to go the proper way about this, you would be setting up a separate project/folder for your frontend application. That application has to be then built, and you attach the built distribution files in your Rails HTML. It depends on your purposes.

使用Rails 6.0.0中的外部JavaScript库的麻烦

你如我软肋 2025-02-09 10:52:19

您需要仿制药。将对象声明为通用类型,该字段为另一个是对象类型的键,而值则作为可分配给对象键的东西。

function setArbitraryPropertyTS<
    T extends object,
    F extends keyof T,
    V extends T[F]
>(
    object: T,
    field: F,
    value: V
) {
    object[field] = value;
}

const obj1 = { a: 'foo', b: 123, c: true };

setArbitraryPropertyTS(obj1, 'a', 'bar');

You'll need generics. Declare the object as a generic type, the field as another that's a key of the object type, and the value as something assignable to that key of the object.

function setArbitraryPropertyTS<
    T extends object,
    F extends keyof T,
    V extends T[F]
>(
    object: T,
    field: F,
    value: V
) {
    object[field] = value;
}

const obj1 = { a: 'foo', b: 123, c: true };

setArbitraryPropertyTS(obj1, 'a', 'bar');

如何使用字符串密钥打字稿动态设置定义的属性?

你如我软肋 2025-02-08 13:09:56

由于CTE是蓝牙5.1的可选功能,因此答案很明确:这取决于。
蓝牙方向查找尚未得到Android的支持,因此需要特定于制造商的API启用CTE(如果智能手机硬件支持)。

Since CTE is an optional feature for Bluetooth 5.1, the answer is clear: it depends.
Bluetooth direction finding is not yet supported by Android, so it would require a manufacturer-specific API to enable CTE (if it is supported by the smartphone hardware).

我可以从智能手机中发送带有音调扩展的蓝牙广告包吗?

你如我软肋 2025-02-08 11:01:48

实现此目的的最简单方法是向输出HTML添加其他CSS。

  1. 创建 style.html 带有以下内容的文件。

     &lt; style&gt;
      li:不(:Last-Child){Margin-Bottom:50px; }
    &lt;/style&gt;
     
  2. 添加 -h style.html 将文件包括在HTML标题部分中。例如:

      $ pandoc main.md -t html5 -o main.html -h style.html
     

请注意,还有许多其他方法可以将其他CSS包括到输出HTML文件中(例如,您可以简单地将&lt; style&gt; 标记标记在Markdown文件中。查看此问题以获取更多信息:带有Pandoc的Inline CSS

The simplest way to achieve this is to add additional CSS to the output HTML.

  1. Create style.html file with the following content.

    <style>
      li:not(:last-child) { margin-bottom: 50px; }
    </style>
    
  2. Add -H style.html to include the file in the HTML header part. For example:

    $ pandoc main.md -t html5 -o main.html -H style.html
    

Note that there are many other ways to include additional CSS to the output HTML file (for example you may simply put the <style> tag inside your markdown file). Check out this question for more info: Inline CSS with Pandoc

pandoc markdown至HTML:如何增加列表项目的边距?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文