November 6, 2010

Python Game and Cipher

I wrote this simple game in Python using the tkinter graphics module.  This is my first attempt at writing a game, so it is very basic but (hopefully) entertaining at the same time.


You are the R2D2 robot, and you dodge the falling stars.  Your score is judged by the number of stars that fall before you die, and there are three different difficulty settings.  The speed at which stars fall is determined by their size; the larger the star, the faster it falls.  When you lose, your high score is saved to a text file so that you can keep your scores when you quit the game.  If you would like to run the game or modify the code, you can download Python from here.  



Here is the code for the game:












from tkinter import *
from sys import getfilesystemencoding
import time
import random


height = 700
width = 700
movement=0
pos=0
size=0
score=0


canvas = Canvas(highlightthickness=0, height=height, width=width)
canvas.master.title("Falling Stars")
if getfilesystemencoding() == 'utf-8':       # only for mac
   canvas.master.call('console', 'hide')
canvas.pack()
pic = PhotoImage(width=width, height=height)
canvas.create_image(0,0,image=pic,anchor=NW)




canvas.create_rectangle(0,0,height,width,fill='black')


floor=canvas.create_rectangle(0,700,700,671,fill='brown',tag='ground')


density=12
def easy():
   global density
   density=20
   return density
def medium():
   global density
   density=8
   return density
def hard():
   global density
   density=5
   return density


easy=Button(canvas.master, text='Easy', command=easy)
easy.pack()
medium=Button(canvas.master, text='Medium',command=medium)
medium.pack()
hard=Button(canvas.master, text='Hard',command=hard)
hard.pack()


global r2,character
r2=PhotoImage(file='right.gif')
r2R=PhotoImage(file='right.gif')
r2L=PhotoImage(file='left.gif')
character=canvas.create_image(370,636, image=r2,tag='character')


def game():
   global pos,movement,character,size,lose,star,lose_screen,density,score,r2
   pos=350
   count=0
   print_score=0
   score=0
   while True:
      x = (random.randint(0,width))
      y = (random.randint(0,height))
      z= random.randint(1,15)


      if z<5:
         size='large'
      elif 4<z<10:
         size='medium'
      elif 11<z:
         size='small'
   
      if count%density==0:
         star=canvas.create_polygon(x,-200+(75//z), x+(200//z),-200+(75//z),x+(40//z),-200+(200//z),x+(100//z),-200,x+(170//z),-200+(200//z),x,-200+(75//z),fill='grey',outline='grey',tag=size)
         score=score+1
      if star-320>4:
         canvas.delete(star-320)
      canvas.move('small',0,6)
      canvas.move('medium',0,10)
      canvas.move('large',0,15)


      
      
      count=count+1
      canvas.delete(print_score)


      print_score=canvas.create_text(350,15,text=("Score:",score),fill='blue',)
      canvas.tag_raise('ground',star)
      
      if pos>=680:
         pos=0
      elif pos<=0:
         pos=680
      canvas.coords('character',pos+20,636)
      pos=pos+movement
      
      lose=str(canvas.find_overlapping(pos,670,pos+40,604))
      
      if lose!= '(1, 2, 4)':
         canvas.create_rectangle(0,0,700,700,fill='green')
         canvas.create_text(350,350,text='You Lose', fill='black')
         canvas.create_text(350,370,text='Press Enter to try again', fill='black')
         canvas.create_text(350,390,text=("Your score was",score), fill='black')
         try:
             f = open("high_score_h.txt", "r")
             try:
                 string = f.read()
                 hscore=(int(string))
             finally:
                    f.close()
         except IOError:
            pass
         if score>hscore:
            try:
                f = open("high_score_h.txt", "w")
                try:
                    f.write(str(score)) 
                    
                finally:
                    f.close()
            except IOError:
                pass
         try:
             f = open("high_score_h.txt", "r")
             try:
                 string = f.read()
                 hscore=(int(string))
             finally:
                    f.close()
         except IOError:
            pass
         canvas.create_text(350,410,text=("Your high score is",hscore), fill='black')


         break
         
      time.sleep(.01)
      canvas.update()


      
      
      


def retry(event):
     x=list(canvas.find_all())
     for item in x:
        if item>4:
           canvas.delete(item)
     game()
        
def keypress(event):
   global  movement,pos, restart,r2




   if (event.keysym=='d' or event.keysym=='Right'):
      movement=7
      r2=PhotoImage(file='right.gif')
      canvas.itemconfigure('character', image=r2)
   elif (event.keysym=='a' or event.keysym=='Left'):
      movement=-7
      r2=PhotoImage(file='left.gif')
      canvas.itemconfigure('character', image=r2)
def keyrelease(event):
   global movement
   if event.keysym=='d' or event.keysym=='Right' or event.keysym=='a' or event.keysym=='Left':
      movement=0






canvas.master.bind("<Key-Return>", retry)
canvas.master.bind("<Key>",keypress)
canvas.master.bind("<KeyRelease>",keyrelease)


####






canvas.after(10,game)


canvas.mainloop()




Images:
ImageShack, share photos, pictures, free image hosting, free video hosting, image hosting, video hosting, photo image hosting site, video hosting site
ImageShack, share photos, pictures, free image hosting, free video hosting, image hosting, video hosting, photo image hosting site, video hosting site

To run the game you will also need to create a blank .txt file called high_score_h in the same folder as the images and the code.


I also recently wrote some code that generates a code.  Input text, and the program will garble it beyond recognition, using an encryption method I invented myself.  Here is the previous paragraph (including this sentence) encrypted:

fAFOUZ_dnpvw}ƒ‡‹“˜Ÿ¢©¶¼¿ÊÑÓÜäåêíñúĄďĔĞ/IYiojkWTUchYkgaWaKWROFBMAANA,K:,AzCtCv'ooznnBNrswuscupwTfUiVRabXOYGRZKMLE-N;F-'Jy!K'-v"tq,sys.qvt-xujnfXjYgUioehVaYVMaNTHtIMTBJO";DOH,"!NYu-su?.pluvhxjotqlVlTYiQeV(TXLTbJNRJUHHQO'HM;E,.)z"vAG;'sqH

The encryption is not one to one- characters will not be the same if they are repeated in the original text.  If you want to see how it works, here is the code:

Encryptor:

import random
#number of spaces in string
y=input()
x=y[:]
spaces=0
answer=[]
for i in x:
    if i==' ':
        spaces+=1
spaceletter=chr(65+spaces)
answer.append(spaceletter)

#placement of spaces in string
for e in range(len(x)):
    if x[e]==' ':
        answer.append(chr(64+e))

answer.append('/')

#create alphabet
alph='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!,.?:;-"'
alph=alph+"'"
alphabet=list(alph)
#changes characters
for b in range(len(x)):
    if x[b]==' ':
        pass
    elif x[b] not in alphabet:
        answer.append(x[b])
    else:
        for i in range(len(alphabet)):
            
            if alphabet[i]==x[b]:
                while (i-b)&lt;0:
                    i+=61
                answer.append(alphabet[i-b])

print(''.join(answer))




Decryption:


y=input()
x=y[:]
answer=[]
alph='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!,.?:;-"'
alph=alph+"'"
alphabet=list(alph)

for i in range(len(x)):
    if x[i]=='/':
        z=i
        spaces=x[1:i]

#creates a list of the propper length
for e in range(z+1,len(x)):
    answer.append(x[e])

#adds spaces in the correct place
for i in range(1,z):
    place=((ord(x[i]))-64)
    answer.insert(place,' ')

    
for i in range(len(answer)):
    if answer[i]==' ':
        pass
    elif answer[i] not in alphabet:
        pass
    else:
        for b in range(len(alphabet)):
             
             if alphabet[b]==answer[i]:
                while (i+b)&gt;60:
                    b-=61
                answer[i]=(alphabet[i+b])
                break

print(''.join(answer))



KDGKRVZ`dis/TZjhoiqfkZNfPbkHTIJGUQC-'T"GIHC'zas.,?Brqyj:lytqhpfsry

No comments:

Post a Comment