using System;
using System.Drawing;
using System.Windows.Forms;
namespace ShipOnWater
{
public partial class Form1 : Form
{
// The ship image
private Image ship = Image.FromFile("ship.png");
// The water image
private Image water = Image.FromFile("water.png");
// The ship position
private Point shipPos = new Point(200, 200);
// The ship speed
private int shipSpeed = 10;
// The water offset
private int waterOffset = 0;
// The water speed
private int waterSpeed = 2;
public Form1()
{
InitializeComponent();
// Set the form size to match the water image size
this.ClientSize = new Size(water.Width, water.Height);
// Set the timer interval to 20 milliseconds
timer1.Interval = 20;
// Start the timer
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Update the water offset
waterOffset += waterSpeed;
// Wrap the water offset around the water image height
waterOffset %= water.Height;
// Invalidate the form to trigger the paint event
this.Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Get the graphics object
Graphics g = e.Graphics;
// Draw the water image twice to create a scrolling effect
g.DrawImage(water, 0, waterOffset - water.Height);
g.DrawImage(water, 0, waterOffset);
// Draw the ship image at the ship position
g.DrawImage(ship, shipPos);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// Move the ship according to the pressed key
switch (e.KeyCode)
{
case Keys.Up:
// Move the ship up
shipPos.Y -= shipSpeed;
break;
case Keys.Down:
// Move the ship down
shipPos.Y += shipSpeed;
break;
case Keys.Left:
// Move the ship left
shipPos.X -= shipSpeed;
break;
case Keys.Right:
// Move the ship right
shipPos.X += shipSpeed;
break;
}
// Clamp the ship position to the form boundaries
shipPos.X = Math.Max(0, Math.Min(shipPos.X, this.ClientSize.Width - ship.Width));
shipPos.Y = Math.Max(0,
Math.Min(shipPos.Y, this.ClientSize.Height - ship.Height));
}
}
}