Over the last year and some change, I've been trying to teach myself to code. I started with Python for no real reason other than there were a number of tutorial sites out there that seemed to be pretty complete.
After going through the tutorials and Python documentation (several times in some cases) I found myself wondering how to get in some badly needed practice. After all, in order to code something you need to have some sort of use case in mind. I had found a number of forums offering up ideas for projects, but most were either way above my head or so simple I completed them in minutes.
Longer projects seemed to only hold my interest if there were some actual need for the functionality. Like parsing proxy logs or cmdb data at work. For everything else, I had trouble keeping focused till the completion of the code.
One day, by chance, I found this: http://inventwithpython.com/
At the time Albert Sweigart had only written the first book, but it was enough to renew my interest in learning the language. It's written so that even those with no working knowledge of programming can start creating games and learning python. It goes through a few command-line based games, into graphics based games teaching skills that can easily be translated into scripting and app development.
If you are interested in simple game development, or Python, I would definitely recommend reading his book either by download (for free) or purchasing a hardcopy . The second book is also now available and goes into even more detail with several new game types and development concepts.
I know this sounds like some sort of plug, but I am in no way being compensated for this endorsement. I am merely a grateful reader of his work.
-newt
Wednesday, March 20, 2013
Wednesday, March 13, 2013
Coding Challenge - Python
So I've been a fan of hackthissite.org for a while now. IT Security has been an interest of mine since I was introduced to computers. They've got tons of hacking challenges to test your skills and teach you new ones.
Just recently though, I noticed that they have coding/scripting challenges now as well. They range from beginner to really difficult, but they've got some really neat ones up there. If you're interested, go register (for free, of course) and try them out for yourself.
The first challenge asks you to code something that can take a number of scrambled words, that were chosen from a file that they provide you with, run the input through a script and produce the unscrambled words in a specific format. i.e. (word1, word2, word3,.....)
Sure you could do it manually, but the page expires a few seconds after the scrambled words are given. So you have to get the scrambled words, run them through your script and submit the output in a few seconds.
There are a ton of ways you could handle this, like sending the output to a file, or console, or even have it go straight to the clipboard so you can paste it into the web form quickly. Even write something to parse the page, pull down the words, and post the output automatically...
Below the break, you can see how I did it using python. Kind of a spoiler if you're planning to try this stuff out yourself, just fyi.
Just recently though, I noticed that they have coding/scripting challenges now as well. They range from beginner to really difficult, but they've got some really neat ones up there. If you're interested, go register (for free, of course) and try them out for yourself.
The first challenge asks you to code something that can take a number of scrambled words, that were chosen from a file that they provide you with, run the input through a script and produce the unscrambled words in a specific format. i.e. (word1, word2, word3,.....)
Sure you could do it manually, but the page expires a few seconds after the scrambled words are given. So you have to get the scrambled words, run them through your script and submit the output in a few seconds.
There are a ton of ways you could handle this, like sending the output to a file, or console, or even have it go straight to the clipboard so you can paste it into the web form quickly. Even write something to parse the page, pull down the words, and post the output automatically...
Below the break, you can see how I did it using python. Kind of a spoiler if you're planning to try this stuff out yourself, just fyi.
Labels:
Challenge,
Code,
hackthissite,
output to file,
Python,
Script
Wednesday, March 6, 2013
Assignment - Python
So, one of my java classes had this assignment a while back to write a command-line application to store user input to a text file. Easy, right? Just loop over the 3 questions and save the user responses on a line in a text file.
Having never worked with Java before, I was surprised at the amount of code necessary to do this. Even without validating user input, the code ended up being around 40 lines.
It got me thinking about how I would do the same thing in python. And I was curious to see how few lines it would take to get the exact same functionality. Here's what I came up with:
file = open("output.txt", 'w')
listOfStuff = []
while True:
productID = raw_input("enter productID: ")
product = raw_input("enter product: ")
price = raw_input("enter price: ")
listOfStuff.append(productID+" "+product+" "+price+ "\n")
blah = raw_input("Coninue? yes or no: ")
if blah in ("no", "nope", "negative"):
break
for i in listOfStuff:
file.write(i)
file.close()
13 lines does it. Sure I should do some input validation and all that best-practice jazz, but I didn't have to implement any of that for the java project either, and I was just trying to get the same output and functionality.
If anyone wants to see the crappy java version of this that I did, I guess I could post that too, just leave a comment, or shoot me a message. I only leave it out because 1) I'm lazy, and 2) I have my doubts about anyone actually reading this blog.
-newt
Having never worked with Java before, I was surprised at the amount of code necessary to do this. Even without validating user input, the code ended up being around 40 lines.
It got me thinking about how I would do the same thing in python. And I was curious to see how few lines it would take to get the exact same functionality. Here's what I came up with:
file = open("output.txt", 'w')
listOfStuff = []
while True:
productID = raw_input("enter productID: ")
product = raw_input("enter product: ")
price = raw_input("enter price: ")
listOfStuff.append(productID+" "+product+" "+price+ "\n")
blah = raw_input("Coninue? yes or no: ")
if blah in ("no", "nope", "negative"):
break
for i in listOfStuff:
file.write(i)
file.close()
13 lines does it. Sure I should do some input validation and all that best-practice jazz, but I didn't have to implement any of that for the java project either, and I was just trying to get the same output and functionality.
If anyone wants to see the crappy java version of this that I did, I guess I could post that too, just leave a comment, or shoot me a message. I only leave it out because 1) I'm lazy, and 2) I have my doubts about anyone actually reading this blog.
-newt
Wednesday, February 27, 2013
99 bottles of beer - Python
This one is pretty useless, I know. I was trying to think up something to code to test out my fledgling Python knowledge back when I was first picking it up. There was a competition online to script something to output the lyrics to "99 bottles of beer on the wall" in the fewest lines possible. There was a category for fewest characters as well. I knew I wasn't good enough to enter such a competition, but I figured I'd try it and see what I could come up with.
Here's what I ended up doing:
def outputLine(x,v):
z = str(x) + " bottle" + v + " of beer on the wall, " + str(x) + " bottle" + v + " of beer. take one down pass it around, " + str(x-1) + " bottles of beer on the wall."
print z
def song():
boosh = range(1, 100)
boosh.reverse()
for x in boosh:
if x == 1:
v = ""
outputLine(x,v)
else:
v = "s"
outputLine(x,v)
x = x - 1
song()
I know now, several shortcuts I could use to shorten it up a bit more, but it's interesting for me to see how I solved a problem a year ago and think about how I would do it now.
-newt
Here's what I ended up doing:
def outputLine(x,v):
z = str(x) + " bottle" + v + " of beer on the wall, " + str(x) + " bottle" + v + " of beer. take one down pass it around, " + str(x-1) + " bottles of beer on the wall."
print z
def song():
boosh = range(1, 100)
boosh.reverse()
for x in boosh:
if x == 1:
v = ""
outputLine(x,v)
else:
v = "s"
outputLine(x,v)
x = x - 1
song()
![]() |
works like a champ |
-newt
Monday, December 17, 2012
Konami code - Python
Okay, so I was playing around with my game trying to figure out how to implement cheats. There's probably a more elegant way to do this, but I'm still pretty new to coding, so give me a break.
Basically I created a pause menu function. All my menu's work by implementing a menu with basic functions and attributes. You just feed the menu function some images to use for the screen, and set up a loop to watch for keystrokes or other input events.
Anyway, for the pause menu, I just have a simple background with two options available to choose from. It watches for input from the up, down, left, right, b, a, keys. (went with the konami code for testing) I set up two variables. code and match. code is an array that holds key strokes while match is used to determine if the keys were pressed in the correct order.
def pause(screen, font):
images = ['menu.png', 'menu1.png']
menu = Menu(images)
menu.imgset = [pygame.image.load(images[0]), pygame.image.load(images[1])]
pygame.sprite.RenderPlain(menu)
clock = pygame.time.Clock()
code = []
match = ['u','u','d','d','l','r','l','r','b','a']
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == KEYDOWN:
if event.type == pygame.QUIT:
terminate()
if event.key == K_UP:
menu.changeup()
code.append('u')
if event.key == K_DOWN:
menu.changedown()
code.append('d')
if event.key == K_LEFT:
code.append('l')
if event.key == K_RIGHT:
code.append('r')
if event.key == K_b:
code.append('b')
if event.key == K_a:
code.append('a')
if event.key == K_RETURN:
if menu.pos == 0:
#shared.PAUSE = False
return False
if menu.pos == 1:
pygame.quit()
sys.exit()
code = code[-10:]
if code == match:
shared.CHEAT = True
code = []
menu.update()
pygame.draw.rect(screen,(0, 0 ,0),(0,0,800,600))
screen.blit(menu.image,menu.rect)
#drawText('Paused', font, screen, 350, 30)
textobj = font.render("Paused", 1, (255,255,255))
textrect = textobj.get_rect()
textrect.topleft = (350, 30)
screen.blit(textobj, textrect)
pygame.display.update()
Here's the bit in the main loop that uses the pause and checks for the cheat variable before changing the background image:
def main():
while 1:
#set up variables, initialize sprites, etc, etc...
.......
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == KEYDOWN:
#throw in a pause key
if event.key == K_p:
pause(screen, font)
#check for cheat and blit images to screen surface
if shared.CHEAT:
screen.blit(backimage2,backrect)
if not shared.CHEAT:
screen.blit(backimage,backrect)
screen.blit(attack.image,attack.rect)
screen.blit(player.image,player.rect)
pygame.display.update()
basically pressing p brings up the pause screen, and while in the pause menu, if the two variables match, it sets the CHEAT variable to true.
You could instead, have it add more "cheat" options to the menu, so you could turn them on and off. The way I did it, leaves the cheat on for the duration of the game. Like I said, there are probably better ways to do it, but this works. I'll probably post the whole game source at some point, but if you'd like to see it now, just let me know and I'll shoot you the source.
-newt
Basically I created a pause menu function. All my menu's work by implementing a menu with basic functions and attributes. You just feed the menu function some images to use for the screen, and set up a loop to watch for keystrokes or other input events.
Anyway, for the pause menu, I just have a simple background with two options available to choose from. It watches for input from the up, down, left, right, b, a, keys. (went with the konami code for testing) I set up two variables. code and match. code is an array that holds key strokes while match is used to determine if the keys were pressed in the correct order.
def pause(screen, font):
images = ['menu.png', 'menu1.png']
menu = Menu(images)
menu.imgset = [pygame.image.load(images[0]), pygame.image.load(images[1])]
pygame.sprite.RenderPlain(menu)
clock = pygame.time.Clock()
code = []
match = ['u','u','d','d','l','r','l','r','b','a']
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == KEYDOWN:
if event.type == pygame.QUIT:
terminate()
if event.key == K_UP:
menu.changeup()
code.append('u')
if event.key == K_DOWN:
menu.changedown()
code.append('d')
if event.key == K_LEFT:
code.append('l')
if event.key == K_RIGHT:
code.append('r')
if event.key == K_b:
code.append('b')
if event.key == K_a:
code.append('a')
if event.key == K_RETURN:
if menu.pos == 0:
#shared.PAUSE = False
return False
if menu.pos == 1:
pygame.quit()
sys.exit()
code = code[-10:]
if code == match:
shared.CHEAT = True
code = []
menu.update()
pygame.draw.rect(screen,(0, 0 ,0),(0,0,800,600))
screen.blit(menu.image,menu.rect)
#drawText('Paused', font, screen, 350, 30)
textobj = font.render("Paused", 1, (255,255,255))
textrect = textobj.get_rect()
textrect.topleft = (350, 30)
screen.blit(textobj, textrect)
pygame.display.update()
Here's the bit in the main loop that uses the pause and checks for the cheat variable before changing the background image:
def main():
while 1:
#set up variables, initialize sprites, etc, etc...
.......
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == KEYDOWN:
#throw in a pause key
if event.key == K_p:
pause(screen, font)
#check for cheat and blit images to screen surface
if shared.CHEAT:
screen.blit(backimage2,backrect)
if not shared.CHEAT:
screen.blit(backimage,backrect)
screen.blit(attack.image,attack.rect)
screen.blit(player.image,player.rect)
pygame.display.update()
basically pressing p brings up the pause screen, and while in the pause menu, if the two variables match, it sets the CHEAT variable to true.
You could instead, have it add more "cheat" options to the menu, so you could turn them on and off. The way I did it, leaves the cheat on for the duration of the game. Like I said, there are probably better ways to do it, but this works. I'll probably post the whole game source at some point, but if you'd like to see it now, just let me know and I'll shoot you the source.
-newt
Calculate Car Loan
![]() |
When run on my linux system |
Here's a simple script for calculating a car loan using java:
package calculateloan;
public class displayFrame extends javax.swing.JFrame {
//set up variables
public float interest;
public float price;
public float dpayment;
public int num_months;
public float results;
public float results1;
public double cubed;
/**
* Creates new form displayFrame
*/
public displayFrame() {
initComponents();
}
..........
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// set default credit rating
interest = 0.15f;
//find out credit rating
if (jRadioButton1.isSelected()){
interest = 0.05f;
}
if (jRadioButton2.isSelected()){
interest = 0.10f;
}
if (jRadioButton3.isSelected()){
interest = 0.15f;
}
//find number of months
if (jComboBox1.getSelectedItem() == "5 years"){
num_months = 60;
}
if (jComboBox1.getSelectedItem() == "10 years"){
num_months = 120;
}
if (jTextField1.getText().isEmpty()){
//set default value for price
price = 15000.0f;
}
if (jTextField1.getText().length() != 0){
//set price from fields if not null
price = Integer.parseInt(jTextField1.getText());
}
if (jTextField2.getText().isEmpty()){
//set default down payment
dpayment = 0.0f;
}
if (jTextField2.getText().length() != 0){
//set down payment if field not null
dpayment = Integer.parseInt(jTextField2.getText());
}
//Print lines to test variable assignment
//System.out.println(price);
//System.out.println(dpayment);
//System.out.println(num_months);
//System.out.println(interest);
//at this point fields are set. we can calculate payment
//the calculation is (payment(rate/12))/(1-(1+rate/12)^-num_months)
//i broke it down into several steps
results = interest/12;
results = price * results;
results1 = interest/12;
results1 += 1;
num_months = -num_months;
cubed = java.lang.Math.pow(results1, num_months);
cubed = 1-cubed;
cubed = results/cubed;
//cubed is now a double with way too many decimal places
//let's do a bit of math to round it to the nearest tenth
//thanks to Obvius for this bit
int tempInteger;
cubed *= 100;
cubed += (double).5;
tempInteger = (int)cubed;
cubed = (double)tempInteger;
cubed /= 100;
jLabel7.setText("Results: " + cubed);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
float[] anArray;
anArray = new float[3];
anArray[0] = 0.05f;
anArray[1] = 0.10f;
anArray[2] = 0.15f;
.........
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new displayFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
.......
}
Where ever you see "......." I've omitted some of the garbage netbeans adds. Obviously this is a snippet from a jframe project and the important bits are in tact. I set up a number of fields, dropdowns, etc, and a button that takes all of it to calculate the loan.
You should be able to do the same thing fairly easy using the design function within netbeans or a similar IDE.
-Newt
Monday, December 10, 2012
Hopefully Helpful
So I was coding a simple python game the other day using pygame, and I thought this might be helpful for someone:
class Test(pygame.sprite.Sprite):
# Constructor function
def __init__(self,x,y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set init speed
self.change_x=0
self.change_y=0
self.facing = 0
# Set height, width
self.image = pygame.image.load('baddie.png')
self.down = [pygame.image.load('baddie.png').convert_alpha(),
pygame.image.load('baddie1.png').convert_alpha(),
pygame.image.load('baddie2.png').convert_alpha(),
pygame.image.load('baddie3.png').convert_alpha(),
pygame.image.load('baddie2.png').convert_alpha(),
pygame.image.load('baddie1.png').convert_alpha()]
self.left = [pygame.image.load('baddiel.png').convert_alpha(),
pygame.image.load('baddiel1.png').convert_alpha(),
pygame.image.load('baddiel2.png').convert_alpha(),
pygame.image.load('baddiel3.png').convert_alpha(),
pygame.image.load('baddiel2.png').convert_alpha(),
pygame.image.load('baddiel1.png').convert_alpha()]
self.right = [pygame.image.load('baddier.png').convert_alpha(),
pygame.image.load('baddier1.png').convert_alpha(),
pygame.image.load('baddier2.png').convert_alpha(),
pygame.image.load('baddier3.png').convert_alpha(),
pygame.image.load('baddier2.png').convert_alpha(),
pygame.image.load('baddier1.png').convert_alpha()]
self.up = [pygame.image.load('baddieu.png').convert_alpha(),
pygame.image.load('baddieu1.png').convert_alpha(),
pygame.image.load('baddieu2.png').convert_alpha(),
pygame.image.load('baddieu3.png').convert_alpha(),
pygame.image.load('baddieu2.png').convert_alpha(),
pygame.image.load('baddieu1.png').convert_alpha()]
self.imgcounter = 0
self.imgvar = 0
# Make our top-left corner a required input for the class
self.rect = self.image.get_rect()
self.rect.topleft = [x,y]
# Change the speed of the player
def changespeed(self,x,y):
self.change_x+=x
self.change_y+=y
# Find a new position for the player
def update(self):
# Get the old position, in case we need to go back to it
old_x=self.rect.topleft[0]
old_y=self.rect.topleft[1]
# Update position according to our speed (vector)
new_x=old_x+self.change_x
new_y=old_y+self.change_y
# Put the player in the new spot
self.rect.topleft = (new_x,new_y)
if self.change_x == 0 and self.change_y == 0:
#self.imgvar = 0
if self.facing == 3:
self.image = self.left[0]
if self.facing == 2:
self.image = self.down[0]
if self.facing == 4:
self.image = self.right[0]
if self.facing == 1:
self.image = self.up[0]
if self.change_x < 0:
self.facing = 3
if self.imgcounter == 0:
self.image = self.left[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.left[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.left)-1:
self.imgvar = 0
#self.image = self.left[self.imgvar]
if self.change_x > 0:
self.facing = 4
if self.imgcounter == 0:
self.image = self.right[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.right[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.right)-1:
self.imgvar = 0
if self.change_y < 0:
self.facing = 1
if self.imgcounter == 0:
self.image = self.up[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.up[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.up)-1:
self.imgvar = 0
if self.change_y > 0:
self.facing = 2
if self.imgcounter == 0:
self.image = self.down[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.down[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.down)-1:
self.imgvar = 0
It's a simple sprite created to help test some animations I created. Keeps track of directions and the update function flips through an array of images. You can easily adjust this to pull in images from a sprite sheet instead of using several image files.
It doesn't really do much else, but it's useful for testing out sprite animations.
-Newt
class Test(pygame.sprite.Sprite):
# Constructor function
def __init__(self,x,y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set init speed
self.change_x=0
self.change_y=0
self.facing = 0
# Set height, width
self.image = pygame.image.load('baddie.png')
self.down = [pygame.image.load('baddie.png').convert_alpha(),
pygame.image.load('baddie1.png').convert_alpha(),
pygame.image.load('baddie2.png').convert_alpha(),
pygame.image.load('baddie3.png').convert_alpha(),
pygame.image.load('baddie2.png').convert_alpha(),
pygame.image.load('baddie1.png').convert_alpha()]
self.left = [pygame.image.load('baddiel.png').convert_alpha(),
pygame.image.load('baddiel1.png').convert_alpha(),
pygame.image.load('baddiel2.png').convert_alpha(),
pygame.image.load('baddiel3.png').convert_alpha(),
pygame.image.load('baddiel2.png').convert_alpha(),
pygame.image.load('baddiel1.png').convert_alpha()]
self.right = [pygame.image.load('baddier.png').convert_alpha(),
pygame.image.load('baddier1.png').convert_alpha(),
pygame.image.load('baddier2.png').convert_alpha(),
pygame.image.load('baddier3.png').convert_alpha(),
pygame.image.load('baddier2.png').convert_alpha(),
pygame.image.load('baddier1.png').convert_alpha()]
self.up = [pygame.image.load('baddieu.png').convert_alpha(),
pygame.image.load('baddieu1.png').convert_alpha(),
pygame.image.load('baddieu2.png').convert_alpha(),
pygame.image.load('baddieu3.png').convert_alpha(),
pygame.image.load('baddieu2.png').convert_alpha(),
pygame.image.load('baddieu1.png').convert_alpha()]
self.imgcounter = 0
self.imgvar = 0
# Make our top-left corner a required input for the class
self.rect = self.image.get_rect()
self.rect.topleft = [x,y]
# Change the speed of the player
def changespeed(self,x,y):
self.change_x+=x
self.change_y+=y
# Find a new position for the player
def update(self):
# Get the old position, in case we need to go back to it
old_x=self.rect.topleft[0]
old_y=self.rect.topleft[1]
# Update position according to our speed (vector)
new_x=old_x+self.change_x
new_y=old_y+self.change_y
# Put the player in the new spot
self.rect.topleft = (new_x,new_y)
if self.change_x == 0 and self.change_y == 0:
#self.imgvar = 0
if self.facing == 3:
self.image = self.left[0]
if self.facing == 2:
self.image = self.down[0]
if self.facing == 4:
self.image = self.right[0]
if self.facing == 1:
self.image = self.up[0]
if self.change_x < 0:
self.facing = 3
if self.imgcounter == 0:
self.image = self.left[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.left[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.left)-1:
self.imgvar = 0
#self.image = self.left[self.imgvar]
if self.change_x > 0:
self.facing = 4
if self.imgcounter == 0:
self.image = self.right[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.right[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.right)-1:
self.imgvar = 0
if self.change_y < 0:
self.facing = 1
if self.imgcounter == 0:
self.image = self.up[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.up[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.up)-1:
self.imgvar = 0
if self.change_y > 0:
self.facing = 2
if self.imgcounter == 0:
self.image = self.down[0]
#self.imgcounter =+ 1
self.imgcounter += 1
self.image = self.down[self.imgvar]
if self.imgcounter > 1:
self.imgcounter = 0
self.imgvar += 1
if self.imgvar > len(self.down)-1:
self.imgvar = 0
It's a simple sprite created to help test some animations I created. Keeps track of directions and the update function flips through an array of images. You can easily adjust this to pull in images from a sprite sheet instead of using several image files.
It doesn't really do much else, but it's useful for testing out sprite animations.
-Newt
Subscribe to:
Posts (Atom)