Draw pixel 2
- Task
Create a window and draw a pixel in it, subject to the following:
- the window is 640 x 480
- the color of the pixel must be yellow (255,255,0)
- the position of the pixel is random
Ada
with Ada.Numerics.Discrete_Random;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Draw_A_Pixel_2 is
Width : constant := 640;
Height : constant := 480;
use SDL.C;
subtype Width_Range is SDL.C.int range 0 .. Width - 1;
subtype Height_Range is SDL.C.int range 0 .. Height - 1;
package Random_Width is new Ada.Numerics.Discrete_Random (Width_Range);
package Random_Height is new Ada.Numerics.Discrete_Random (Height_Range);
Width_Gen : Random_Width.Generator;
Height_Gen : Random_Height.Generator;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
procedure Wait is
use type SDL.Events.Event_Types;
Event : SDL.Events.Events.Events;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
Random_Width.Reset (Width_Gen);
Random_Height.Reset (Height_Gen);
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Draw a pixel 2",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Renderer.Set_Draw_Colour ((255, 255, 0, 255));
Renderer.Draw (Point => (X => Random_Width.Random (Width_Gen),
Y => Random_Height.Random (Height_Gen)));
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Draw_A_Pixel_2;
C
Same as the Draw_a_pixel task, uses the random number functions of stdlib.h to plot a random point. Requires the WinBGIm library.
#include<graphics.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(NULL));
initwindow(640,480,"Yellow Random Pixel");
putpixel(rand()%640,rand()%480,YELLOW);
getch();
return 0;
}
Delphi
program Draw_a_pixel2;
{$APPTYPE CONSOLE}
uses
Windows,
Messages,
SysUtils;
const
WIN_WIDTH = 640;
WIN_HEIGHT = 480;
var
Msg: TMSG;
LWndClass: TWndClass;
hMainHandle: HWND;
procedure Paint(Handle: hWnd); forward;
procedure ReleaseResources;
begin
PostQuitMessage(0);
end;
function WindowProc(hWnd, Msg: Longint; wParam: wParam; lParam: lParam): Longint; stdcall;
begin
case Msg of
WM_PAINT:
Paint(hWnd);
WM_DESTROY:
ReleaseResources;
end;
Result := DefWindowProc(hWnd, Msg, wParam, lParam);
end;
procedure CreateWin(W, H: Integer);
var
Title: string;
begin
LWndClass.hInstance := hInstance;
with LWndClass do
begin
lpszClassName := 'OneYellowPixel';
Style := CS_PARENTDC or CS_BYTEALIGNCLIENT;
hIcon := LoadIcon(hInstance, 'MAINICON');
lpfnWndProc := @WindowProc;
hbrBackground := COLOR_BTNFACE + 1;
hCursor := LoadCursor(0, IDC_ARROW);
end;
Title := Format('Draw a YELLOW pixel random position in [%d, %d] ', [WIN_WIDTH,
WIN_HEIGHT]);
RegisterClass(LWndClass);
hMainHandle := CreateWindow(LWndClass.lpszClassName, Pchar(Title), WS_CAPTION
or WS_MINIMIZEBOX or WS_SYSMENU or WS_VISIBLE, ((GetSystemMetrics(SM_CXSCREEN)
- W) div 2), ((GetSystemMetrics(SM_CYSCREEN) - H) div 2), W, H, 0, 0, hInstance, nil);
end;
procedure ShowModal;
begin
while GetMessage(Msg, 0, 0, 0) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
procedure Paint(Handle: hWnd);
var
ps: PAINTSTRUCT;
Dc: HDC;
begin
Dc := BeginPaint(Handle, ps);
// Fill bg with black
FillRect(Dc, ps.rcPaint, CreateSolidBrush($0));
// Do the magic
SetPixel(Dc, Random(WIN_WIDTH), Random(WIN_HEIGHT), $FFFF);
EndPaint(Handle, ps);
end;
begin
Randomize;
CreateWin(WIN_WIDTH, WIN_HEIGHT);
ShowModal();
end.
Factor
USING: kernel random raylib.ffi ;
640 480 2dup "random yellow pixel" init-window [ random ] bi@
60 set-target-fps [ window-should-close ] [
begin-drawing BLACK clear-background 2dup YELLOW draw-pixel
end-drawing
] until close-window
FreeBASIC
' version 04-07-2018
' compile with: fbc -s console
' or: fbc -s gui
Screen 18, 24 ' Screen 18: 640x480, 24bit colordepth
'ScreenRes 640, 480, 24 ' Screenres: 640x480, 24bit colordepth
If ScreenPtr = 0 Then
Print "Error setting video mode!"
End
End If
Randomize Timer
Dim As UInteger x = Rnd * 640, y = Rnd * 480
PSet (x, y), RGB(255,255,0) ' yellow
' empty keyboard buffer
While Inkey <> "" : Wend
WindowTitle "0, 0 is top left, pixel is at " & x & ", " & y & " hit any key to end program"
Sleep
End
Go
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"math/rand"
"time"
)
func main() {
rect := image.Rect(0, 0, 640, 480)
img := image.NewRGBA(rect)
// Use blue background, say.
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)
// Set color of a random pixel to yellow
yellow := color.RGBA{255, 255, 0, 255}
width := img.Bounds().Dx()
height := img.Bounds().Dy()
rand.Seed(time.Now().UnixNano())
x := rand.Intn(width)
y := rand.Intn(height)
img.Set(x, y, yellow)
// Check there's exactly one random yellow pixel.
cmap := map[color.Color]string{blue: "blue", yellow: "yellow"}
for i := 0; i < width; i++ {
for j := 0; j < height; j++ {
c := img.At(i, j)
if cmap[c] == "yellow" {
fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j)
}
}
}
}
- Output:
Sample output:
The color of the pixel at (525, 163) is yellow
J
See also Draw a pixel. Note that this pixel will be nearly invisible on most screens. There's very low contrast between yellow and white, and single pixels may be difficult to see on "modern" hardware. Remedying these visual problems would require going outside the requirements of the task. You might change the color, for example to black with glrgb 0 0 0
and/or changing the radius to include more pixels, for example 8 with glpen 8 1
require 'gl2'
coinsert 'jgl2'
wd{{)n pc Rosetta closeok;cc task isidraw; set task wh 640 480;pshow}}
glpaint glpixel ?640 480 [ glpen 1 1 [ glrgb 255 255 0 [ glclear ''
JavaScript
let w = window.open("", "", "width=640,height=480");
let canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
w.document.body.appendChild(canvas);
w.document.body.style.margin = 0;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#FFFF00";
let x = Math.random() * 641;
let y = Math.random() * 481;
ctx.fillRect(x, y, 1, 1);
Julia
using Gtk, Graphics
const can = @GtkCanvas()
const win = GtkWindow(can, "Draw a Pixel 2", 640, 480)
draw(can) do widget
ctx = getgc(can)
set_source_rgb(ctx, 255, 255, 0)
x = rand(collect(1:639))
y = rand(collect(1:480))
println("The pixel is at $x, $y.")
move_to(ctx, x, y)
line_to(ctx, x + 1, y)
stroke(ctx)
end
draw(can)
show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
wait(cond)
Kotlin
This is a variation of the Draw a pixel task and so therefore is the code to accomplish it.
// Version 1.2.41
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.util.Random
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
val rand = Random()
val bbs = BasicBitmapStorage(640, 480)
with (bbs) {
fill(Color.white) // say
val x = rand.nextInt(image.width)
val y = rand.nextInt(image.height)
setPixel(x, y, Color.yellow)
// check there's exactly one random yellow pixel
for (i in 0 until image.width) {
for (j in 0 until image.height) {
if (getPixel(i, j) == Color.yellow) {
println("The color of the pixel at ($i, $j) is yellow")
}
}
}
}
}
- Output:
Sample output:
The color of the pixel at (296, 15) is yellow
Nim
import random
import sdl2
discard sdl2.init(INIT_EVERYTHING)
let window = createWindow("Pixel", 300, 300, 640, 480, SDL_WINDOW_SHOWN)
let renderer = createRenderer(window, -1, Renderer_Accelerated)
randomize()
renderer.clear()
renderer.setDrawColor((255u8, 255u8, 0u8, 0u8))
let x = rand(639)
let y = rand(479)
renderer.drawPoint(x.cint, y.cint)
renderer.present()
delay(5000)
Objeck
use Game.SDL2;
use Game.Framework;
class DrawPixel {
@framework : GameFramework;
function : Main(args : String[]) ~ Nil {
DrawPixel->New()->Run();
}
New() {
@framework := GameFramework->New(640, 480, "RGB");
@framework->SetClearColor(Color->New(0, 0, 0));
}
method : Run() ~ Nil {
if(@framework->IsOk()) {
e := @framework->GetEvent();
x := Int->Random(640);
y := Int->Random(480);
quit := false;
while(<>quit) {
@framework->FrameStart();
@framework->Clear();
# process input
while(e->Poll() <> 0) {
if(e->GetType() = EventType->SDL_QUIT) {
quit := true;
};
};
@framework->GetRenderer()->SetDrawColor(255, 255, 0, 0);
@framework->GetRenderer()->DrawPoint(x, y);
@framework->Show();
@framework->FrameEnd();
};
}
else {
"--- Error Initializing Game Environment ---"->ErrorLine();
return;
};
leaving {
@framework->Quit();
};
}
}
Perl
use Gtk3 '-init';
my $width = 640;
my $height = 480;
my $window = Gtk3::Window->new();
$window->set_default_size($width, $height);
$window->set_border_width(10);
$window->set_title("Draw Pixel 2");
$window->set_app_paintable(TRUE);
my $da = Gtk3::DrawingArea->new();
$da->signal_connect('draw' => \&draw_in_drawingarea);
$window->add($da);
$window->show_all();
Gtk3->main;
sub draw_in_drawingarea
{
my ($widget, $cr, $data) = @_;
$cr->set_source_rgb(1, 1, 0);
$cr->set_line_width(1);
$cr->rectangle( int rand $width , int rand $height, 1, 1);
$cr->stroke;
}
Phix
Pixel jumps around randomly, twice a second.
-- -- demo\rosetta\Draw_pixel_2.exw -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/) atom {w,h} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) cdCanvasPixel(cddbuffer, rand(w), rand(h), CD_YELLOW) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_BLACK) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) IupUpdate(canvas) return IUP_IGNORE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=240x250") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas,`TITLE="Draw pixel"`) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) Ihandle timer = IupTimer(Icallback("timer_cb"), 500) -- (2 fps) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
Processing
//Aamrun, 26th June 2022
size(640,480);
stroke(#ffff00);
ellipse(random(640),random(480),1,1);
Python
import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
pos = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
root = Tkinter.Tk()
can = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
can.create_rectangle( pos*2,outline='yellow' )
can.pack()
root.title('press ESCAPE to quit')
root.bind('<Escape>',lambda e : root.quit())
root.mainloop()
draw_pixel_2()
Racket
#lang racket/gui
(define WIDTH 640)
(define HEIGHT 480)
(define COLOR (make-color 255 255 0))
(define BACKGROUND-COLOR (make-color 0 0 0))
(define frame (new frame%
[label "Draw Pixel"]
[width WIDTH]
[height HEIGHT]))
(new canvas% [parent frame]
[paint-callback
(λ (canvas dc)
(send dc set-background BACKGROUND-COLOR)
(send dc clear)
(send dc set-pen COLOR 1 'solid)
(send dc draw-point (random WIDTH) (random HEIGHT)))])
(send frame show #t)
Raku
(formerly Perl 6)
Coordinates of random pixel displayed in window title. To make the single pixel show up better I filled in the drawing area background with black to get better contrast.
use GTK::Simple;
use GTK::Simple::DrawingArea;
use Cairo;
my ($w, $h) = 640, 480;
my ($x, $y) = (^$w).pick, (^$h).pick;
my $app = GTK::Simple::App.new(:title("Draw Pixel 2 @ $x,$y"));
my $da = GTK::Simple::DrawingArea.new;
gtk_simple_use_cairo;
$app.set-content( $da );
$app.border-width = 5;
$da.size-request($w, $h);
sub rect-do( $d, $ctx ) {
given $ctx {
.rgb(0, 0, 0);
.rectangle(0, 0, $w, $h);
.fill;
.rgb(1, 1, 0);
.rectangle($x, $y, 1, 1);
.fill;
}
}
my $ctx = $da.add-draw-handler( &rect-do );
$app.run;
Ring
# Project : Draw pixel 2
load "guilib.ring"
new qapp {
nwidth = 320
nheight= 240
win1 = new qwidget() {
setwindowtitle("Draw Pixel 2")
setgeometry(100,100,640,480)
label1 = new qlabel(win1) {
setgeometry(10,10,640,480)
settext("")
}
new qpushbutton(win1) {
setgeometry(200,400,100,30)
settext("draw")
setclickevent("draw()")
}
new qpushbutton(win1) {
setgeometry(300,400,100,30)
settext("get pixel color")
setclickevent("PixelColor()")
}
show()
}
exec()
}
func draw()
p1 = new qpicture()
color = new qcolor() {
setrgb(255,255,0,255)
}
pen = new qpen() {
setcolor(color)
setwidth(10)
}
new qpainter() {
begin(p1)
setpen(pen)
x = random(nwidth-1) + 1
y = random(nheight-1) + 1
see "x = " + x + " y = " + y + nl
drawpoint(x,y)
endpaint()
}
label1 { setpicture(p1) show() }
func PixelColor()
oapp = new qapp(0,null) {
screen = win1.windowhandle().screen()
pixmap = screen.grabwindow(0,0,0,-1,-1)
image = pixmap.toimage()
color = image.pixel(100,100)
mycolor = new qcolor()
mycolor.setrgb(255,255,0,255)
see nl+"red : " + mycolor.red() + nl
see "green : " + mycolor.green() + nl
see "blue : " + mycolor.blue() + nl
}
Outputimage:
Scala
Java Swing Interoperability
- Output:
See it yourself by running in your browser either by Scastie (remote JVM).
import java.awt.image.BufferedImage
import java.awt.Color
import scala.language.reflectiveCalls
object RgbBitmap extends App {
// Even Javanese style testing is still possible.
private val img0 =
new RgbBitMap(50, 60) { // Wrappers to enable adhoc Javanese style
def getPixel(x: Int, y: Int) = this(x, y)
def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c
}
class RgbBitMap(val dim: (Int, Int)) {
private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
def apply(x: Int, y: Int) = new Color(image.getRGB(x, y))
def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB)
def fill(c: Color) = {
val g = image.getGraphics
g.setColor(c)
g.fillRect(0, 0, width, height)
}
def width = dim._1
def height = dim._2
}
private val (x,y) = (util.Random.nextInt(50), util.Random.nextInt(60))
img0.fill(Color.CYAN)
img0.setPixel(x, y, Color.BLUE)
// Testing in Java style
assert(img0.getPixel(x, y) == Color.BLUE)
assert(img0.width == 50)
assert(img0.height == 60)
println("Tests successfully completed with no errors found.")
}
V (Vlang)
import gg
import gx
import rand
const (
win_width = 640
win_height = 480
x = rand.int_in_range(1, win_width) or {exit(-1)}
y = rand.int_in_range(1, win_height) or {exit(-1)}
)
fn main() {
mut app := gg.new_context(
width: win_width
height: win_height
frame_fn: frame
window_title: 'Pixel 2'
)
app.run()
}
fn frame(mut ctx gg.Context) {
ctx.begin()
ctx.draw_pixel(x, y, gx.yellow)
ctx.end()
}
Wren
import "dome" for Window
import "graphics" for Canvas, Color
import "random" for Random
class Game {
static init() {
Window.title = "Draw a pixel 2"
Window.resize(320, 240)
Canvas.resize(320, 240)
var yellow = Color.rgb(255, 255, 0)
var rand = Random.new()
var randX = rand.int(320)
var randY = rand.int(240)
Canvas.pset(randX, randY, yellow)
}
static update() {}
static draw(dt) {}
static getRGB(col) { "{%(col.r), %(col.g), %(col.b)}" }
}
XPL0
This is all that's required on the Raspberry Pi version of XPL0.
[SetFB(640, 480, 24); Point(Ran(640), Ran(480), $FFFF00)]