Python3 codes
1. Flappy bird
Installation : pip install pygame
Code : # Fork of [Link] from itertools import cycle import
random import sys import pygame from [Link] import * FPS = 30 SCREENWIDTH =
288 SCREENHEIGHT = 512 PIPEGAPSIZE = 100 # gap between upper and lower part of pipe
BASEY = SCREENHEIGHT * 0.79 # image, sound and hitmask dicts IMAGES, SOUNDS,
HITMASKS = {}, {}, {} # list of all possible players (tuple of 3 positions of flap) PLAYERS_LIST = (
# red box ( 'assets/sprites/[Link]', 'assets/sprites/[Link]',
'assets/sprites/[Link]', ), # blue box ( 'assets/sprites/bluebox-
[Link]', 'assets/sprites/[Link]', 'assets/sprites/bluebox-
[Link]', ), # yellow box ( 'assets/sprites/[Link]',
'assets/sprites/[Link]', 'assets/sprites/[Link]', ), ) #
list of backgrounds BACKGROUNDS_LIST = ( 'assets/sprites/[Link]',
'assets/sprites/[Link]', ) # list of pipes PIPES_LIST = ( 'assets/sprites/pipe-
[Link]', 'assets/sprites/[Link]', ) try: xrange except NameError: xrange =
range def main(): global SCREEN, FPSCLOCK [Link]() FPSCLOCK =
[Link]() # Fullscreen scaled output SCREEN =
[Link].set_mode((SCREENWIDTH, SCREENHEIGHT), [Link] |
[Link]) [Link].set_caption('Flappy Box') # numbers sprites for
score display IMAGES['numbers'] =
([Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha(),
[Link]('assets/sprites/[Link]').convert_alpha()) # game over sprite
IMAGES['gameover'] = [Link]('assets/sprites/[Link]').convert_alpha()
# message sprite for welcome screen IMAGES['message'] =
[Link]('assets/sprites/[Link]').convert_alpha() # base (ground) sprite
IMAGES['base'] = [Link]('assets/sprites/[Link]').convert_alpha() # sounds
soundExt = '.ogg' SOUNDS['die'] = [Link]('assets/audio/die' + soundExt)
SOUNDS['hit'] = [Link]('assets/audio/hit' + soundExt) SOUNDS['point'] =
[Link]('assets/audio/point' + soundExt) SOUNDS['wing'] =
[Link]('assets/audio/wing' + soundExt) while True: # select random
background sprites randBg = [Link](0, len(BACKGROUNDS_LIST) - 1)
IMAGES['background'] = [Link](BACKGROUNDS_LIST[randBg]).convert() #
select random player sprites randPlayer = [Link](0, len(PLAYERS_LIST) - 1)
IMAGES['player'] = ( [Link](PLAYERS_LIST[randPlayer]
[0]).convert_alpha(), [Link](PLAYERS_LIST[randPlayer]
[1]).convert_alpha(), [Link](PLAYERS_LIST[randPlayer]
[2]).convert_alpha(), ) # select random pipe sprites pipeindex =
[Link](0, len(PIPES_LIST) - 1) IMAGES['pipe'] =
( [Link]([Link](PIPES_LIST[pipeindex]).convert_alpha(),
False, True), [Link](PIPES_LIST[pipeindex]).convert_alpha(), ) #
hismask for pipes HITMASKS['pipe'] = ( getHitmask(IMAGES['pipe'][0]),
getHitmask(IMAGES['pipe'][1]), ) # hitmask for player HITMASKS['player'] = (
getHitmask(IMAGES['player'][0]), getHitmask(IMAGES['player'][1]),
getHitmask(IMAGES['player'][2]), ) movementInfo = showWelcomeAnimation()
crashInfo = mainGame(movementInfo) showGameOverScreen(crashInfo) def
showWelcomeAnimation(): """Shows welcome screen animation of flappy box""" # index
of player to blit on screen playerIndex = 0 playerIndexGen = cycle([0, 1, 2, 1]) # iterator
used to change playerIndex after every 5th iteration loopIter = 0 playerx =
int(SCREENWIDTH * 0.2) playery = int((SCREENHEIGHT - IMAGES['player'][0].get_height()) /
2) messagex = int((SCREENWIDTH - IMAGES['message'].get_width()) / 2) messagey =
int(SCREENHEIGHT * 0.12) basex = 0 # amount by which base can maximum shift to left
baseShift = IMAGES['base'].get_width() - IMAGES['background'].get_width() # player shm
for up-down motion on welcome screen playerShmVals = {'val': 0, 'dir': 1} while True:
for event in [Link](): if [Link] == QUIT or ([Link] == KEYDOWN and
[Link] == K_ESCAPE): [Link]() [Link]() if [Link] ==
KEYDOWN and ([Link] == K_SPACE or [Link] == K_UP) or [Link] ==
MOUSEBUTTONDOWN: # make first flap sound and return values for mainGame
SOUNDS['wing'].play() return { 'playery': playery + playerShmVals['val'],
'basex': basex, 'playerIndexGen': playerIndexGen, } # adjust playery,
playerIndex, basex if (loopIter + 1) % 5 == 0: playerIndex = next(playerIndexGen)
loopIter = (loopIter + 1) % 30 basex = -((-basex + 4) % baseShift)
playerShm(playerShmVals) # draw sprites [Link](IMAGES['background'], (0, 0))
[Link](IMAGES['player'][playerIndex], (playerx, playery + playerShmVals['val']))
[Link](IMAGES['message'], (messagex, messagey)) [Link](IMAGES['base'],
(basex, BASEY)) [Link]() [Link](FPS) def
mainGame(movementInfo): score = playerIndex = loopIter = 0 playerIndexGen =
movementInfo['playerIndexGen'] playerx, playery = int(SCREENWIDTH * 0.2),
movementInfo['playery'] basex = movementInfo['basex'] baseShift =
IMAGES['base'].get_width() - IMAGES['background'].get_width() # get 2 new pipes to add
to upperPipes lowerPipes list newPipe1 = getRandomPipe() newPipe2 = getRandomPipe()
# list of upper pipes upperPipes = [ { 'x': SCREENWIDTH + 200, 'y':
newPipe1[0]['y'] }, { 'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y':
newPipe2[0]['y'] }, ] # list of lowerpipe lowerPipes = [ { 'x':
SCREENWIDTH + 200, 'y': newPipe1[1]['y'] }, { 'x': SCREENWIDTH + 200 +
(SCREENWIDTH / 2), 'y': newPipe2[1]['y'] }, ] pipeVelX = -4 # player velocity,
max velocity, downward accleration, accleration on flap playerVelY = -9 # player's velocity
along Y, default same as playerFlapped playerMaxVelY = 10 # max vel along Y, max descend
speed playerMinVelY = -8 # min vel along Y, max ascend speed playerAccY = 1 # players
downward accleration playerRot = 45 # player's rotation playerVelRot = 3 # angular
speed playerRotThr = 20 # rotation threshold playerFlapAcc = -9 # players speed on
flapping playerFlapped = False # True when player flaps while True: for event in
[Link](): if [Link] == QUIT or ([Link] == KEYDOWN and [Link]
== K_ESCAPE): [Link]() [Link]() if [Link] == KEYDOWN and
([Link] == K_SPACE or [Link] == K_UP) or [Link] == MOUSEBUTTONDOWN:
if playery > -2 * IMAGES['player'][0].get_height(): playerVelY = playerFlapAcc
playerFlapped = True SOUNDS['wing'].play() # check for crash here
crashTest = checkCrash({'x': playerx, 'y': playery, 'index': playerIndex}, upperPipes,
lowerPipes) if crashTest[0]: return {'y': playery, 'groundCrash': crashTest[1], 'basex':
basex, 'upperPipes': upperPipes, 'lowerPipes': lowerPipes, 'score': score, 'playerVelY':
playerVelY, 'playerRot': playerRot} # check for score playerMidPos = playerx +
IMAGES['player'][0].get_width() / 2 for pipe in upperPipes: pipeMidPos = pipe['x'] +
IMAGES['pipe'][0].get_width() / 2 if pipeMidPos <= playerMidPos < pipeMidPos + 4:
score += 1 SOUNDS['point'].play() # playerIndex basex change if (loopIter +
1) % 3 == 0: playerIndex = next(playerIndexGen) loopIter = (loopIter + 1) % 30
basex = -((-basex + 100) % baseShift) # rotate the player if playerRot > -90:
playerRot -= playerVelRot # player's movement if playerVelY < playerMaxVelY and
not playerFlapped: playerVelY += playerAccY if playerFlapped: playerFlapped
= False # more rotation to cover the threshold (calculated in visible rotation)
playerRot = 45 playerHeight = IMAGES['player'][playerIndex].get_height() playery +=
min(playerVelY, BASEY - playery - playerHeight) # move pipes to left for uPipe, lPipe
in zip(upperPipes, lowerPipes): uPipe['x'] += pipeVelX lPipe['x'] += pipeVelX
# add new pipe when first pipe is about to touch left of screen if len(upperPipes) > 0 and 0
< upperPipes[0]['x'] < 5: newPipe = getRandomPipe()
[Link](newPipe[0]) [Link](newPipe[1]) # remove first
pipe if its out of the screen if len(upperPipes) > 0 and upperPipes[0]['x'] < -IMAGES['pipe']
[0].get_width(): [Link](0) [Link](0) # draw sprites
[Link](IMAGES['background'], (0, 0)) for uPipe, lPipe in zip(upperPipes, lowerPipes):
[Link](IMAGES['pipe'][0], (uPipe['x'], uPipe['y'])) [Link](IMAGES['pipe'][1],
(lPipe['x'], lPipe['y'])) [Link](IMAGES['base'], (basex, BASEY)) # print score so
player overlaps the score showScore(score) # Player rotation has a threshold
visibleRot = playerRotThr if playerRot <= playerRotThr: visibleRot = playerRot
playerSurface = [Link](IMAGES['player'][playerIndex], visibleRot)
[Link](playerSurface, (playerx, playery)) [Link]()
[Link](FPS) def showGameOverScreen(crashInfo): """crashes the player down ans
shows gameover image""" score = crashInfo['score'] playerx = SCREENWIDTH * 0.2
playery = crashInfo['y'] playerHeight = IMAGES['player'][0].get_height() playerVelY =
crashInfo['playerVelY'] playerAccY = 2 playerRot = crashInfo['playerRot'] playerVelRot =
7 basex = crashInfo['basex'] upperPipes, lowerPipes = crashInfo['upperPipes'],
crashInfo['lowerPipes'] # play hit and die sounds SOUNDS['hit'].play() if not
crashInfo['groundCrash']: SOUNDS['die'].play() while True: for event in
[Link](): if [Link] == QUIT or ([Link] == KEYDOWN and [Link]
== K_ESCAPE): [Link]() [Link]() if [Link] == KEYDOWN and
([Link] == K_SPACE or [Link] == K_UP) or [Link] == MOUSEBUTTONDOWN:
if playery + playerHeight >= BASEY - 1: return # player y shift if playery +
playerHeight < BASEY - 1: playery += min(playerVelY, BASEY - playery - playerHeight)
# player velocity change if playerVelY < 15: playerVelY += playerAccY # rotate
only when it's a pipe crash if not crashInfo['groundCrash']: if playerRot > -90:
playerRot -= playerVelRot # draw sprites [Link](IMAGES['background'], (0, 0))
for uPipe, lPipe in zip(upperPipes, lowerPipes): [Link](IMAGES['pipe'][0],
(uPipe['x'], uPipe['y'])) [Link](IMAGES['pipe'][1], (lPipe['x'], lPipe['y']))
[Link](IMAGES['base'], (basex, BASEY)) showScore(score) playerSurface =
[Link](IMAGES['player'][1], playerRot) [Link](playerSurface,
(playerx, playery)) [Link](IMAGES['gameover'], (50, 180)) [Link](FPS)
[Link]() def playerShm(playerShm): """oscillates the value of
playerShm['val'] between 8 and -8""" if abs(playerShm['val']) == 8: playerShm['dir'] *=
-1 if playerShm['dir'] == 1: playerShm['val'] += 1 else: playerShm['val'] -= 1 def
getRandomPipe(): """returns a randomly generated pipe""" # y of gap between upper
and lower pipe gapY = [Link](0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY +=
int(BASEY * 0.2) pipeHeight = IMAGES['pipe'][0].get_height() pipeX = SCREENWIDTH + 10
return [ { 'x': pipeX, 'y': gapY - pipeHeight }, # upper pipe { 'x':
pipeX, 'y': gapY + PIPEGAPSIZE }, # lower pipe ] def showScore(score):
"""displays score in center of screen""" scoreDigits = [int(x) for x in list(str(score))]
totalWidth = 0 # total width of all numbers to be printed for digit in scoreDigits:
totalWidth += IMAGES['numbers'][digit].get_width() Xoffset = (SCREENWIDTH - totalWidth)
/ 2 for digit in scoreDigits: [Link](IMAGES['numbers'][digit], (Xoffset,
SCREENHEIGHT * 0.1)) Xoffset += IMAGES['numbers'][digit].get_width() def
checkCrash(player, upperPipes, lowerPipes): """returns True if player collders with base or
pipes.""" pi = player['index'] player['w'] = IMAGES['player'][0].get_width() player['h'] =
IMAGES['player'][0].get_height() # if player crashes into ground if player['y'] + player['h']
>= BASEY - 1: return [True, True] else: playerRect = [Link](player['x'],
player['y'], player['w'], player['h']) pipeW = IMAGES['pipe'][0].get_width() pipeH =
IMAGES['pipe'][0].get_height() for uPipe, lPipe in zip(upperPipes, lowerPipes): #
upper and lower pipe rects uPipeRect = [Link](uPipe['x'], uPipe['y'], pipeW,
pipeH) lPipeRect = [Link](lPipe['x'], lPipe['y'], pipeW, pipeH) # player and
upper/lower pipe hitmasks pHitMask = HITMASKS['player'][pi] uHitmask =
HITMASKS['pipe'][0] lHitmask = HITMASKS['pipe'][1] # if player collided with
upipe or lpipe uCollide = pixelCollision(playerRect, uPipeRect, pHitMask, uHitmask)
lCollide = pixelCollision(playerRect, lPipeRect, pHitMask, lHitmask) if uCollide or
lCollide: return [True, False] return [False, False] def pixelCollision(rect1, rect2,
hitmask1, hitmask2): """Checks if two objects collide and not just their rects""" rect =
[Link](rect2) if [Link] == 0 or [Link] == 0: return False x1, y1 = rect.x -
rect1.x, rect.y - rect1.y x2, y2 = rect.x - rect2.x, rect.y - rect2.y for x in xrange([Link]):
for y in xrange([Link]): if hitmask1[x1 + x][y1 + y] and hitmask2[x2 + x][y2 + y]:
return True return False def getHitmask(image): """returns a hitmask using an image's
alpha.""" mask = [] for x in xrange(image.get_width()): [Link]([]) for y in
xrange(image.get_height()): mask[x].append(bool(image.get_at((x, y))[3])) return
mask if __name__ == '__main__': main()
2. Touchtracer
Installation: pip install kivy
Code : ''' Touch Tracer Line Drawing Demonstration
======================================= This demonstrates tracking each touch
registered to a device. You should see a basic background image. When you press and hold
the mouse, you should see cross-hairs with the coordinates written next to them. As you drag,
it leaves a trail. Additional information, like pressure, will be shown if they are in your device's
[Link]. .. note:: A function `calculate_points` handling the points which will be drawn
has by default implemented a delay of 5 steps. To get more precise visual results lower the
value of the optional keyword argument `steps`. This program specifies an icon, the file
[Link], in its App subclass. It also uses the [Link] file as the source for drawing the
trails which are white on transparent. The file [Link] describes the application. The
file [Link] is used to package the application for use with the Kivy Launcher Android
application. For Android devices, you can copy/paste this directory into
/sdcard/kivy/touchtracer on your Android device. ''' __version__ = '1.0' import kivy
[Link]('1.0.6') from [Link] import App from [Link] import FloatLayout
from [Link] import Label from [Link] import Color, Rectangle, Point,
GraphicException from random import random from math import sqrt def
calculate_points(x1, y1, x2, y2, steps=5): dx = x2 - x1 dy = y2 - y1 dist = sqrt(dx * dx + dy
* dy) if dist < steps: return o = [] m = dist / steps for i in range(1, int(m)): mi =
i/m lastx = x1 + dx * mi lasty = y1 + dy * mi [Link]([lastx, lasty]) return o
class Touchtracer(FloatLayout): def on_touch_down(self, touch): win =
self.get_parent_window() ud = [Link] ud['group'] = g = str([Link]) pointsize
=5 if 'pressure' in [Link]: ud['pressure'] = [Link] pointsize =
([Link] * 100000) ** 2 ud['color'] = random() with [Link]:
Color(ud['color'], 1, 1, mode='hsv', group=g) ud['lines'] =
[ Rectangle(pos=(touch.x, 0), size=(1, [Link]), group=g),
Rectangle(pos=(0, touch.y), size=([Link], 1), group=g), Point(points=(touch.x,
touch.y), source='[Link]', pointsize=pointsize, group=g)] ud['label'] =
Label(size_hint=(None, None)) self.update_touch_label(ud['label'], touch)
self.add_widget(ud['label']) [Link](self) return True def on_touch_move(self,
touch): if touch.grab_current is not self: return ud = [Link] ud['lines']
[0].pos = touch.x, 0 ud['lines'][1].pos = 0, touch.y index = -1 while True:
try: points = ud['lines'][index].points oldx, oldy = points[-2], points[-1]
break except: index -= 1 points = calculate_points(oldx, oldy, touch.x,
touch.y) # if pressure changed create a new point instruction if 'pressure' in ud:
if not .95 < ([Link] / ud['pressure']) < 1.05: g = ud['group'] pointsize
= ([Link] * 100000) ** 2 with [Link]: Color(ud['color'], 1, 1,
mode='hsv', group=g) ud['lines'].append( Point(points=(),
source='[Link]', pointsize=pointsize, group=g)) if points: try:
lp = ud['lines'][-1].add_point for idx in range(0, len(points), 2):
lp(points[idx], points[idx + 1]) except GraphicException: pass
ud['label'].pos = [Link] import time t = int([Link]()) if t not in ud:
ud[t] = 1 else: ud[t] += 1 self.update_touch_label(ud['label'], touch) def
on_touch_up(self, touch): if touch.grab_current is not self: return
[Link](self) ud = [Link] [Link].remove_group(ud['group'])
self.remove_widget(ud['label']) def update_touch_label(self, label, touch): [Link] =
'ID: %s\nPos: (%d, %d)\nClass: %s' % ( [Link], touch.x, touch.y,
touch.__class__.__name__) label.texture_update() [Link] = [Link]
[Link] = label.texture_size[0] + 20, label.texture_size[1] + 20 class TouchtracerApp(App):
title = 'Touchtracer' icon = '[Link]' def build(self): return Touchtracer() def
on_pause(self): return True if __name__ == '__main__': TouchtracerApp().run()
3. Draw_elipse
Installation: pip install kivy
Code: from [Link] import App from [Link] import Widget from [Link]
import Color, Ellipse class MyPaintWidget(Widget): def on_touch_down(self, touch):
with [Link]: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d / 2,
touch.y - d / 2), size=(d, d)) class MyPaintApp(App): def build(self): return
MyPaintWidget() if __name__ == '__main__': MyPaintApp().run()
4. Note pad (text editor)
Installation: pip install tkinter
Code: from tkinter import * from [Link] import * from [Link]
import * from [Link] import Font from [Link] import * import
file_menu import edit_menu import format_menu import help_menu root = Tk()
[Link]("Text Editor-Untiltled") [Link]("300x250+300+300")
[Link](width=400, height=400) text = ScrolledText(root, state='normal', height=400,
width=400, wrap='word', pady=2, padx=3, undo=True) [Link](fill=Y, expand=1)
text.focus_set() menubar = Menu(root) file_menu.main(root, text, menubar)
edit_menu.main(root, text, menubar) format_menu.main(root, text, menubar)
help_menu.main(root, text, menubar) [Link]()