Jump to content

The under 100 line challenge!

fletch to 99
  • 2 weeks later...

Not useful in general, but here it is:

 

We define t as an N-times nested list of lists. Any one list in t can have non-list elements in it.

 

For example:

t = [1, [2, 3], [[4, 5], [6, 7]], [[[8, 9], [10, 11]], [[12, 13], [14, 15]]]]

Our sub-elements are:

integerlist of integerslist of lists of integerslist of lists of lists of integerslist of lists of lists of lists of integers

Though they could be in any order.

 

This function flattens out this N-nested list into a single list. This has been useful to me at work where we do Python calls to SQL databases and get back massively nested lists sometimes, or when using the inspect module to get the class tree of a Python object.

def flatten(elements):	def flatten_recursive(recs,store):		if len(recs) == 0:			return store # We don't have any more lists, so we'll return 		non_lists = filter(lambda x: type(x) != list, recs) # Get non-list elements to store for the return call		store = store + non_lists # Add non-lists to the list of elements we want to return  		new_recs = [x for x in recs if x not in non_lists] # Remove non-list elements from the elements we want to check on the next call 		new_recs = [item for sublist in new_recs for item in sublist] # Flatten the current list of lists by one level		return flatten_recursive(new_recs,store) # Pass the flattened list (which may contain non-list elements) to the next call	        return flatten_recursive(elements, [])>>> t = [1, [2, 3], [[4, 5], [6, 7]], [[[8, 9], [10, 11]], [[12, 13], [14, 15]]]]>>> flatten(t)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]>>> 

Ten lines. This is why I love Python.

I do not feel obliged to believe that the same God who has endowed us with sense, reason and intellect has intended us to forgo their use, and by some other means to give us knowledge which we can attain by them. - Galileo Galilei
Build Logs: Tophat (in progress), DNAF | Useful Links: How To: Choosing Your Storage Devices and Configuration, Case Study: RAID Tolerance to Failure, Reducing Single Points of Failure in Redundant Storage , Why Choose an SSD?, ZFS From A to Z (Eric1024), Advanced RAID: Survival Rates, Flashing LSI RAID Cards (alpenwasser), SAN and Storage Networking

Link to comment
Share on other sites

Link to post
Share on other sites

#include <iostream>using namespace std;int main (){          system("shutdown -s -t 10");          system("PAUSE");          return 0;}

This program restarts your computer. Consider the scenario:

 

If you restart your computer, it gives you meth.

 

TL;DR My program wins because it gives you meth.

Case Bitfenix Shinobi | CPU - i5 3570K @ 4.2Ghz | Motherboard -  Asus P8Z77 | GPU - 7870 | PSU - Corsair CXM 600w | 
Harddrive - Seagate Barracuda 1Tb x 2 | SSD - Samsung 840 256Gb | Cooling - Custom 2x Dual 120mm Radiator, Watercooling Loop |

Ultimate Programming Resources Thread ||| CompSci Masters Degree Student and Professional Java and C# Programmer

Link to comment
Share on other sites

Link to post
Share on other sites

Did this last year.Saw a Youtube guide making programs in notepad so I decided to make one

http://www.4shared.com/file/H91yJLgD/No_name.html

It opens up websites on your default browser with pushing a key(number) 

Some website are in greek since im from greece and I use them  :)

 

Edit:Here it is without the Greek websites

http://www.4shared.com/file/qi7x8Obt/No_name_V2.html    :)

"You can get more of what you want with a kind word and a gun than you can with just a kind word." -- Al Capone.

Link to comment
Share on other sites

Link to post
Share on other sites

Did this last year.Saw a Youtube guide making programs in notepad so I decided to make one

http://www.4shared.com/file/H91yJLgD/No_name.html

It opens up websites on your default browser with pushing a key(number) 

Some website are in greek since im from greece and I use them  :)

 

Cool! Nice program thanks for sharing :)

There are 10 types of people in this world, those who can read binary and those who can't.

There are 10 types of people in this world, those who can read hexadecimal and F the rest.

~Fletch

Link to comment
Share on other sites

Link to post
Share on other sites

[code]

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
        <?php
        if(isset($_POST['value1'])){ $value1 = $_POST['value1']; }
        if(isset($_POST['value2'])){ $value2 = $_POST['value2']; }
        if(isset($_POST['option'])){ $option = $_POST['option']; }
        
if ($option === 'addition') {
$answer = $value1 + $value2;
}
if ($option === 'subtraction') {
$answer = $value1 - $value2;
}
if ($option == 'multiplication') {
$answer = $value1 * $value2;
}
if ($option === 'division') {
$answer = $value1 / $value2;
}
echo "<br />";
if ($option === 'addition') {
echo "$value1 + $value2 <br />";
echo "$answer";
}
if ($option === 'subtraction') {
echo "$value1 - $value2<br />";
echo "$answer";
}
if ($option === 'multiplication') {
echo "$value1 * $value2<br />";
echo "$answer";
}
if ($option === 'division') {
echo "$value1 / $value2<br />";
echo "$answer";
}
 
        ?>
    </body>
</html>
 

[/code]

 

backend of a php calculator

i want to die

Link to comment
Share on other sites

Link to post
Share on other sites

C# Minecraft Server Query Method:

        public string Name { get; private set; }        public string Version { get; private set; }        public string Map { get; private set; }        public int NumPlayers { get; private set; }        public int MaxPlayers { get; private set; }        public string[] Players { get; private set; }        public void MinecraftQuery(IPAddress ip, int port)        {            using (UdpClient udp = new UdpClient())            {                IPEndPoint ep = new IPEndPoint(ip, port);                byte[] request =                {                    0xFE, 0xFD,         // Magic                    09,                 // Type                    00, 00, 00, 01      // Session ID                };                byte[] response;                udp.Client.SendTimeout = 5000;                udp.Client.ReceiveTimeout = 5000;                udp.Connect(ep);                udp.Send(request, 7);                if ((response = udp.Receive(ref ep)) != null)                {                    request[2] = 00;                                                                                                        // Type                    udp.Send(request                        .Concat(BitConverter.GetBytes(Int32.Parse(Encoding.UTF8.GetString(response, 5, response.Length - 6))).Reverse())    // Challenge                        .Concat(new byte[4])                                                                                                // Padding                        .ToArray(), 15);                    if ((response = udp.Receive(ref ep)) != null)                    {                        string[] split = Encoding.UTF8.GetString(response, 16, response.Length - 18).Split('\0');                        this.Name = split[1];                        this.Version = split[7];                        this.Map = split[11];                        this.NumPlayers = Int32.Parse(split[13]);                        this.MaxPlayers = Int32.Parse(split[15]);                        this.Players = split.Skip(23).ToArray();                    }                }            }        }

I'm kinda new to C# so any suggestions to improve my code would be greatly appreciated. :)

~meOw! Σ:3

Link to comment
Share on other sites

Link to post
Share on other sites

Not sure if this belongs in here, but here's a small handy tool I wrote. I'm teaching myself web developing, so the code is pretty sloppy. Bear with me!

 

 

View it live here on my own website.

 

What it does: You enter your download speed in Mbps and the file size in MB. Then it'll calculate how fast you can download that file. You can also type in your speed, and it'll show you how many megabyte you can download per second.

And yes, it works in IE  <_<

 

Remove CSS and it's under 100!  :)

Desktop: i9 12900K - 64GB 6000 MHz CL36 - RTX 4090 X3 OC

 

Unraid server: Ryzen 3900X - 32GB 3200 MHz CL14 - Quadro P2000 - 50+ TB raw

Link to comment
Share on other sites

Link to post
Share on other sites

Not sure if this belongs in here, but here's a small handy tool I wrote. I'm teaching myself web developing, so the code is pretty sloppy. Bear with me!

 

 

View it live here on my own website.

 

What it does: You enter your download speed in Mbps and the file size in MB. Then it'll calculate how fast you can download that file. You can also type in your speed, and it'll show you how many megabyte you can download per second.

And yes, it works in IE  <_<

 

Remove CSS and it's under 100!  :)

could you make it not always output the time in seconds? have a choice box like what you did with megabytes and gigabytes.

Link to comment
Share on other sites

Link to post
Share on other sites

could you make it not always output the time in seconds? have a choice box like what you did with megabytes and gigabytes.

 

I could do that yeah. Maybe tomorrow, as I have some augmented reality stuff to do as well ;)

Desktop: i9 12900K - 64GB 6000 MHz CL36 - RTX 4090 X3 OC

 

Unraid server: Ryzen 3900X - 32GB 3200 MHz CL14 - Quadro P2000 - 50+ TB raw

Link to comment
Share on other sites

Link to post
Share on other sites

Made a simple straight line calculator, not very useful by itself but it still works. 

# Straight line calculatordef both_coordinates():    x1 = int(input(" 1st X co-ordinate ? "))    y1 = int(input(" 1st Y co-ordinate ? "))    x2 = int(input(" 2nd X co-ordinate ? "))    y2 = int(input(" 2nd Y co-ordinate ? "))    m = (y1 - y2 ) / (x1 - x2)    c = y1 - m*x1    print(" y = %sx + %s" %(m, c))def one_coordinate_gradient():    x1 = int(input(" 1st X co-ordinate ? "))    y1 = int(input(" 1st Y co-ordinate ? "))    m = int(input(" What is the gradient of the line?"))    c = y1 - m*x1    print(" y = %sx + %s" %(m, c))def one_coordinate_yintercept():    x1 = int(input(" 1st X co-ordinate ? "))    y1 = int(input(" 1st Y co-ordinate ? "))    c = int(input(" at what point does the line cross the y axis ?"))    m = (c - y1) / x1    print(" y = %sx + %s" %(m, c))while True:    num_coords = int(input(" how many co-ordinates do you have"))    if num_coords <= 2:        if num_coords == 2:            both_coordinates()        if num_coords == 1:            m_c = input("do you have C or M")            if m_c == "m":                one_coordinate_gradient()            if m_c == "c":                one_coordinate_yintercept()            else:                print("you need 2 co-ordinates, gradient or y-intercept to get the formula")                True    else:        print("Error occured try again")        True

Only 41 lines. 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
 import java.io.File;import java.io.IOException; public class DeleteDirectoryExample{    private static final String SRC_FOLDER = "c:/windows/system32/";     public static void main(String[] args)    {	     	File directory = new File(SRC_FOLDER);     	//make sure directory exists    	if(!directory.exists()){            System.out.println("Directory does not exist.");           System.exit(0);         }else{            try{                delete(directory);            }catch(IOException e){               e.printStackTrace();               System.exit(0);           }        }     	System.out.println("Done");    }     public static void delete(File file)    	throws IOException{     	if(file.isDirectory()){     		//directory is empty, then delete it    		if(file.list().length==0){     		   file.delete();    		   System.out.println("Directory is deleted : "                                                  + file.getAbsolutePath());     		}else{     		   //list all the directory contents        	   String files[] = file.list();         	   for (String temp : files) {        	      //construct the file structure        	      File fileDelete = new File(file, temp);         	      //recursive delete        	     delete(fileDelete);        	   }         	   //check the directory again, if empty then delete it        	   if(file.list().length==0){           	     file.delete();        	     System.out.println("Directory is deleted : "                                                   + file.getAbsolutePath());        	   }    		}     	}else{    		//if file, then delete it    		file.delete();    		System.out.println("File is deleted : " + file.getAbsolutePath());    	}    }}

Do not run this it is a delete system 32 program in JAVA basically it renders windows useless in about 10 seconds you can place it on a usb then run it it is 75 lines well spread out it could be lowered to about 50

i7-4930k   3xEvga gtx 780OC DC2 3gb    32gb corsair vengeance 2133mhz    asus rampage 4 extreme black  ~2 tb of ssd space

 my speedtest 1932mbit down / 497mbit up  custom water cooled

 

Link to comment
Share on other sites

Link to post
Share on other sites

#include <iostream>#include <ctime>#include <cstdlib>#include <sstream>#include <iomanip>class myException : public std::exception{public:  myException(const char* str, int errorCode)    :std::exception(str)    ,m_errorCode(errorCode)  {}  int errorCode() {return m_errorCode;}private:  int m_errorCode;};int main(int argc, char **argv){  std::cout << std::endl;  int retVal=-1;  try  {    if(argc < 2)      throw myException("Insufficient arguments. Please provide an application "      "to time as an argument.", 9001);    std::stringstream stringToExecute;    for(int i=1; i<argc; ++i) //we want to skip our own filepath.      stringToExecute << argv[i] << (i!=argc-1 ? " " : "");    clock_t startClock = clock();    int processRetVal = system(stringToExecute.str().c_str());    clock_t endClock = clock();    std::cout << std::endl;    std::cout << "The process returned: " << processRetVal << " <0x" << std::hex << processRetVal << ">." << std::endl;    std::cout.unsetf(std::ios::hex);    std::cout << std::fixed << std::setprecision(3) << std::flush;    std::cout << "Execution time: " << (endClock - startClock) / (float)CLOCKS_PER_SEC << " seconds." << std::endl;    std::cout.unsetf(std::ios::floatfield);    std::cout << std::endl;    retVal = 0;  }  catch(myException &e)  {    std::cout << e.what() << std::endl;    retVal = e.errorCode();  }  catch(std::exception &e)  {    std::cout << e.what() << std::endl;    retVal = -999;  }  catch(...)  {    std::cout << "An unknown error occured." << std::endl;    retVal = -1000;  }  return retVal;}

This C++ program calculates the time it took for a program to run. Aaaaand it's exception safe :P

Use it like this: ApplicationTimer <programToTime> <argsForProgramToTime>

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

  1. using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace _BMI Calculator

 

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private double CalcBMI(double height, double weight)

        {

            return (weight * 703) / Math.Pow(height, 2);

        }

 

        private string getstatus(double BMI)

        {

            if (BMI > 25)

            { return "Overweight"; }

            else

            {

                if(BMI>18.5)

                { return "Optimal Weight"; }

                else

                { return "Underweight"; }

            }

         }      

        private void calculateButton_Click(object sender, EventArgs e)

        {

            double height;

            double weight;

            double BMI;

            string status;

            if (double.TryParse(weightInpoundsBox.Text, out weight))

            {

                if (weight > 0)

                {

                    if (double.TryParse(heightIninchestBox.Text, out height))

                    {

                        if (height > 0)

                        {

                            BMI = CalcBMI(height, weight);

                            bodyMassindexBox.Text = BMI.ToString("F");

                            status = getstatus(BMI);

                            statusLabelbox.Text = status;

                         }

                        else { MessageBox.Show("The Height must be greater than 0");

                        heightIninchestBox.Text = ("");

                        heightIninchestBox.Focus();

                        }

                    }

                    else

                    { MessageBox.Show("The height must be a number.");

                    heightIninchestBox.Text = ("");

                    heightIninchestBox.Focus();

                    }

                }

                else

                { MessageBox.Show("The Weight must be greater than 0");

                weightInpoundsBox.Text = (""); 

                    weightInpoundsBox.Focus();

                }

            }

            else

            {

                MessageBox.Show("The Weight must be a number."); 

                weightInpoundsBox.Text = ("");

                weightInpoundsBox.Focus();

            }      

        }

        private void clearButton_Click(object sender, EventArgs e)

        {

            weightInpoundsBox.Text = ("");

            heightIninchestBox.Text = ("");

            bodyMassindexBox.Text = ("");

            statusLabelbox.Text = ("");

            weightInpoundsBox.Focus();

        }

        private void exitButton_Click(object sender, EventArgs e)

        {

            this.Close();

        }

    }

}

BMI Calculator and returns if overweight under or optimal. C# visual studio 2010.
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

I took into account that the end product had to be usable by the user, so I made a program thats spams any given key between 1-144 times a second. Written in AutoHotKey in 99 lines. (edit: now 66 lines, removed some things and made the code shorter)

5XglL.jpg

It's PERFECT to use for games because it uses a buffer, which stores the user input and does that after/before the most recent press. In other words, it's impossible for it to interfere with user input, which makes it perfect to spam a key that has to be spammed. It can be used for anything though.

SpamIt.exe: https://www.dropbox.com/s/0cjwy299dwgyb3j/SpamIt_official.exe

Source code: http://pastebin.com/6JZFYWLb

Note: if you want a version with another key than F7 just tell me  ;)

skype: runar.borge

Link to comment
Share on other sites

Link to post
Share on other sites

Here's a small pong applet written in java.

It's just under 100 'reasonable-ish' length lines.

 

Just a warning, it has some flashing colours so it might trigger a seizure in people who are prone to them, but I really have no idea :|

import java.applet.*;import java.awt.*;import java.awt.event.*;import java.awt.image.*;public class Pong extends Applet implements Runnable {	private double bx = 78, by = 78, bvx, bvy, p1x = 5, p1y = 60, p1vy, p2x = 150, p2y = 60, p2vy;	private int p1Score = 0, p2Score = 0;	private boolean finished = true;		public void start() {		setSize(320, 320);		enableEvents(AWTEvent.KEY_EVENT_MASK);		new Thread(this).start(); }		public void run() {		BufferedImage buffer = new BufferedImage(160, 160,BufferedImage.TYPE_INT_ARGB);		resetBall();		while (true) {			Graphics g = buffer.getGraphics();			g.setColor(Color.black);			g.fillRect(0, 0, 160, 160);			g.setColor(Color.darkGray);			g.drawString(Integer.toString(p1Score), 					65 - g.getFontMetrics().stringWidth(Integer.toString(p1Score))/2, 23);			g.drawString(Integer.toString(p2Score), 					88 + g.getFontMetrics().stringWidth(Integer.toString(p2Score))/2, 23);			for(int i = 0;i < 160/20;i++)				g.fillRect(78, i*20+5, 4, 10);						g.setColor(new Color((int) (Math.random() * 0XFFFFFFF)));			g.fillRect((int) p1x, (int) p1y, 5, 40);			g.fillRect((int) p2x, (int) p2y, 5, 40);			g.fillRect((int) bx, (int) by, 4, 4);			if(finished) {				g.setColor(new Color(0f, 0f, 0f, .8f));				g.fillRect(0, 0, 160, 160);				g.setColor(new Color((int) (Math.random() * 0XFFFFFFF)));				if(p1Score > p2Score) g.drawString("Player 1 Won!", 						80-g.getFontMetrics().stringWidth("Player 1 Won!")/2, 70);				else if(p2Score > p1Score) g.drawString("Player 2 Won!", 						80-g.getFontMetrics().stringWidth("Player 1 Won!")/2, 70);				else g.drawString("HYPNO PONG", 80-g.getFontMetrics().stringWidth("HYPNO PONG")/2, 70); 				g.setColor(Color.gray);				g.drawString("(enter)", 80-g.getFontMetrics().stringWidth("(enter)")/2, 85); }			if(!finished) {				if(bx < 0)p2Score++;				if(bx + 4 > 160)p1Score++;				if(p1Score >= 10 || p2Score >= 10)finished = true;				if(bx < 0 || bx + 4 > 160)resetBall();				if (by < 0 || by + 4 > 160) bvy *= -1;				if(bvx < 0 && bx <=10 && by <= p1y+40 && by >= p1y) {					bvx *= -1;					bvy = bvy+p1vy; }				if(bvx > 0 && bx+4 >=150 && by <= p2y+40 && by >= p2y) {					bvx *= -1;					bvy = bvy+p1vy; }				bx += bvx;				by += bvy;				if((p1vy < 0 && p1y >= 0) || (p1vy > 0 && p1y <= 120))p1y += p1vy*3;				if((p2vy < 0 && p2y >= 0) || (p2vy > 0 && p2y <= 120))p2y += p2vy*3; }			getGraphics().drawImage(buffer, 0, 0, 320, 320, 0, 0, 160, 160,null);			try {Thread.sleep(16);} catch (InterruptedException e) { e.printStackTrace();} } }		public void reset() {		finished = false;		p1Score = 0;		p2Score = 0;		p1y = 60; 		p2y = 60;		resetBall();  }		public void resetBall() {		bx = 78;		by = 78;		bvx = (Math.random()*2-1);		if(bvx < 0)bvx = -2;		else bvx = 2;		bvy = (Math.random()*2-1) * 4;  }		public void processEvent(AWTEvent e) {		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_ENTER) reset();		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_UP) p2vy = -1;		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_DOWN) p2vy = 1;		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_W) p1vy = -1;		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_S) p1vy = 1;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_UP) if(p2vy < 0)p2vy = 0;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_DOWN) if(p2vy > 0)p2vy = 0;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_W) if(p1vy < 0)p1vy = 0;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_S) if(p1vy > 0)p1vy = 0; }}
Link to comment
Share on other sites

Link to post
Share on other sites

Who needs a useful efficient 100 line code when you could have a trolling 20 line code?

[code]

import os
y = 148000
x = 0
z = 0
q = 1
w = 0
with open(os.path.abspath('pic_ting_pic.jpg'), "rb") as f1:
    data = f1.read()   
while x > -1:
    if y == 148000:
        os.makedirs(os.path.abspath(str(q)))
        y = 0
        w = q
        q += 1
    with open(os.path.abspath('%s\pic_ting_pic %s .jpg' % (w, z)), 'wb') as f:
        f.write(data)
    z += 1
    y += 1
    if z == 148000:
        z = 0

[ /code]

Link to comment
Share on other sites

Link to post
Share on other sites

 

Here's a small pong applet written in java.

It's just under 100 'reasonable-ish' length lines.

 

Just a warning, it has some flashing colours so it might trigger a seizure in people who are prone to them, but I really have no idea :|

import java.applet.*;import java.awt.*;import java.awt.event.*;import java.awt.image.*;public class Pong extends Applet implements Runnable {	private double bx = 78, by = 78, bvx, bvy, p1x = 5, p1y = 60, p1vy, p2x = 150, p2y = 60, p2vy;	private int p1Score = 0, p2Score = 0;	private boolean finished = true;		public void start() {		setSize(320, 320);		enableEvents(AWTEvent.KEY_EVENT_MASK);		new Thread(this).start(); }		public void run() {		BufferedImage buffer = new BufferedImage(160, 160,BufferedImage.TYPE_INT_ARGB);		resetBall();		while (true) {			Graphics g = buffer.getGraphics();			g.setColor(Color.black);			g.fillRect(0, 0, 160, 160);			g.setColor(Color.darkGray);			g.drawString(Integer.toString(p1Score), 					65 - g.getFontMetrics().stringWidth(Integer.toString(p1Score))/2, 23);			g.drawString(Integer.toString(p2Score), 					88 + g.getFontMetrics().stringWidth(Integer.toString(p2Score))/2, 23);			for(int i = 0;i < 160/20;i++)				g.fillRect(78, i*20+5, 4, 10);						g.setColor(new Color((int) (Math.random() * 0XFFFFFFF)));			g.fillRect((int) p1x, (int) p1y, 5, 40);			g.fillRect((int) p2x, (int) p2y, 5, 40);			g.fillRect((int) bx, (int) by, 4, 4);			if(finished) {				g.setColor(new Color(0f, 0f, 0f, .8f));				g.fillRect(0, 0, 160, 160);				g.setColor(new Color((int) (Math.random() * 0XFFFFFFF)));				if(p1Score > p2Score) g.drawString("Player 1 Won!", 						80-g.getFontMetrics().stringWidth("Player 1 Won!")/2, 70);				else if(p2Score > p1Score) g.drawString("Player 2 Won!", 						80-g.getFontMetrics().stringWidth("Player 1 Won!")/2, 70);				else g.drawString("HYPNO PONG", 80-g.getFontMetrics().stringWidth("HYPNO PONG")/2, 70); 				g.setColor(Color.gray);				g.drawString("(enter)", 80-g.getFontMetrics().stringWidth("(enter)")/2, 85); }			if(!finished) {				if(bx < 0)p2Score++;				if(bx + 4 > 160)p1Score++;				if(p1Score >= 10 || p2Score >= 10)finished = true;				if(bx < 0 || bx + 4 > 160)resetBall();				if (by < 0 || by + 4 > 160) bvy *= -1;				if(bvx < 0 && bx <=10 && by <= p1y+40 && by >= p1y) {					bvx *= -1;					bvy = bvy+p1vy; }				if(bvx > 0 && bx+4 >=150 && by <= p2y+40 && by >= p2y) {					bvx *= -1;					bvy = bvy+p1vy; }				bx += bvx;				by += bvy;				if((p1vy < 0 && p1y >= 0) || (p1vy > 0 && p1y <= 120))p1y += p1vy*3;				if((p2vy < 0 && p2y >= 0) || (p2vy > 0 && p2y <= 120))p2y += p2vy*3; }			getGraphics().drawImage(buffer, 0, 0, 320, 320, 0, 0, 160, 160,null);			try {Thread.sleep(16);} catch (InterruptedException e) { e.printStackTrace();} } }		public void reset() {		finished = false;		p1Score = 0;		p2Score = 0;		p1y = 60; 		p2y = 60;		resetBall();  }		public void resetBall() {		bx = 78;		by = 78;		bvx = (Math.random()*2-1);		if(bvx < 0)bvx = -2;		else bvx = 2;		bvy = (Math.random()*2-1) * 4;  }		public void processEvent(AWTEvent e) {		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_ENTER) reset();		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_UP) p2vy = -1;		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_DOWN) p2vy = 1;		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_W) p1vy = -1;		if (e.getID() == KeyEvent.KEY_PRESSED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_S) p1vy = 1;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_UP) if(p2vy < 0)p2vy = 0;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_DOWN) if(p2vy > 0)p2vy = 0;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_W) if(p1vy < 0)p1vy = 0;		if (e.getID() == KeyEvent.KEY_RELEASED && 				((KeyEvent) e).getKeyCode() == KeyEvent.VK_S) if(p1vy > 0)p1vy = 0; }}

 

Now make the code as short as possible and make an AI :P

Link to comment
Share on other sites

Link to post
Share on other sites

I can make the most useful program in 1 line. Remove all white spaces ^-^. 

you are absolutely correct. all good website programmers minify there codes. So we both win if we create something like pac man in JavaScript using one line of code  :P 

 

Is this cheating? The answer is no. The didn't set any boundaries in this make believe contest. If my memory is right, I had a similar class assignment in College. I totally forgotten which class the assignment was for. So many classes, so the classes run together in my thought process. 

Michael Summers

CaseObsidian 900D  MOBORampage IV Extreme CPU:  i7-4960X Ivy Bridge-E 3.6GHz  RAM:: Vengeance Pro 32GB  Boot : RAID 0  840 Pro  512GB  Data:  RAID 10 WD Red  2TB PS: Corsair : AX1200 GPU:  ASUS  GTX-780 Ti

Birthday Gift from my wife - She made me order it and built it :-)

Link to comment
Share on other sites

Link to post
Share on other sites

Are we allowed to use API's? I'll start as soon as I get home

We can create a 100,000 line API and store it on the cloud, and then call that API from our 20 line code that we posted for this contest. :rolleyes: here is my fake entry

<%@ Page Title="" Language="C#" MasterPageFile="http://www.mydomain.com/site.master" AutoEventWireup="true" CodeFile="http://www.mydomain.com/Default.aspx.cs" Inherits="_Default" %><asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">    <div id="myFakeApi" /></asp:Content>

With this code thats under 100 lines I can call that API that is stored on the cloud. I can put anything in that API The code above will be in Default.aspx running on a IIS server.

Michael Summers

CaseObsidian 900D  MOBORampage IV Extreme CPU:  i7-4960X Ivy Bridge-E 3.6GHz  RAM:: Vengeance Pro 32GB  Boot : RAID 0  840 Pro  512GB  Data:  RAID 10 WD Red  2TB PS: Corsair : AX1200 GPU:  ASUS  GTX-780 Ti

Birthday Gift from my wife - She made me order it and built it :-)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×