package lect78_impl.view; import java.awt.*; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.File; /** * @overview A class that handles sprite rendering for game objects */ public class Sprite { private BufferedImage image; private int x, y; private int width, height; private double rotation; private boolean usesFallback; /** * @effects * Initialize this as a new Sprite with given image and dimensions * If image loading fails, creates a fallback colored rectangle */ public Sprite(String imagePath, int width, int height) { this.width = width; this.height = height; this.rotation = 0; this.usesFallback = false; try { System.out.println("Attempting to load image: " + imagePath); File file = new File(imagePath); if (!file.exists()) { System.out.println("File does not exist: " + file.getAbsolutePath()); createFallbackImage(); return; } this.image = ImageIO.read(file); System.out.println("Image loaded successfully"); } catch (Exception e) { System.out.println("Failed to load image: " + e.getMessage()); createFallbackImage(); } } /** * @effects Creates a fallback image when the requested image cannot be loaded */ private void createFallbackImage() { usesFallback = true; this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = this.image.createGraphics(); // Create a more visible fallback image g.setColor(Color.GREEN); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); g.drawRect(0, 0, width-1, height-1); // Draw a direction indicator g.drawLine(width/2, height/2, width/2, 0); g.dispose(); System.out.println("Created fallback image"); } /** * @effects Sets the position of this sprite */ public void setPosition(int x, int y) { this.x = x; this.y = y; } /** * @effects Sets the rotation of this sprite in degrees */ public void setRotation(double degrees) { this.rotation = degrees; } /** * @effects Draws this sprite to the specified graphics context */ public void draw(Graphics2D g2d) { if (image != null) { // Simple drawing without rotation g2d.drawImage(image, x, y, width, height, null); // Draw direction indicator int centerX = x + width/2; int centerY = y + height/2; double rad = Math.toRadians(rotation); int dirX = centerX + (int)(Math.cos(rad) * (width/2)); int dirY = centerY + (int)(Math.sin(rad) * (height/2)); g2d.setColor(Color.RED); g2d.drawLine(centerX, centerY, dirX, dirY); // Debug: Draw center point if (usesFallback) { g2d.setColor(Color.RED); g2d.fillOval(centerX - 2, centerY - 2, 4, 4); } } } /** * @effects Gets the bounding rectangle of this sprite */ public Rectangle getBounds() { return new Rectangle(x, y, width, height); } }