def tap(x, y): "Store starting point or draw shape." start = state['start'] if start is None: state['start'] = vector(x, y) else: shape = state['shape'] end = vector(x, y) shape(start, end) state['start'] = None
def move(): "Move pacman and all ghosts." writer.undo() writer.write(state['score']) clear() if valid(pacman + aim): pacman.move(aim) index = offset(pacman) if tiles[index] == 1: tiles[index] = 2 state['score'] += 1 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 square(x, y) up() goto(pacman.x + 10, pacman.y + 10) dot(20, 'yellow') for point, course in ghosts: if valid(point + course): point.move(course) else: options = [ vector(5, 0), vector(-5, 0), vector(0, 5), vector(0, -5), ] plan = choice(options) course.x = plan.x course.y = plan.y up() goto(point.x + 10, point.y + 10) dot(20, 'red') update() for point, course in ghosts: if abs(pacman - point) < 20: return ontimer(move, 100)
def move(): "Move ball and targets." if randrange(40) == 0: y = randrange(-150, 150) target = vector(200, y) targets.append(target) for target in targets: target.x -= 0.5 if inside(ball): speed.y -= 0.35 ball.move(speed) dupe = targets.copy() targets.clear() for target in dupe: if abs(target - ball) > 13: targets.append(target) draw() for target in targets: if not inside(target): return ontimer(move, 50)
def tap(x, y): "Respond to screen tap." onscreenclick(None) x = floor(x, 200) y = floor(y, 200) tile = vector(x, y) index = len(guesses) if tile != pattern[index]: exit() guesses.append(tile) flash(tile) if len(guesses) == len(pattern): grow() onscreenclick(tap)
1. Change the board. 2. Change the number of ghosts. 3. Change where pacman starts. 4. Make the ghosts faster/slower. 5. Make the ghosts smarter. """ from random import choice from turtle import * from freegames import floor, vector state = {'score': 0} path = Turtle(visible=False) writer = Turtle(visible=False) aim = vector(5, 0) pacman = vector(-40, -80) ghosts = [ [vector(-180, 160), vector(5, 0)], [vector(-180, -160), vector(0, 5)], [vector(100, 160), vector(0, -5)], [vector(100, -160), vector(-5, 0)], ] tiles = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
"""Snake, classic arcade game. Exercises 1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. """ from turtle import * from random import randrange from freegames import square, vector food = vector(0, 0) snake = [vector(10, 0)] aim = vector(0, -10) def change(x, y): "Change snake direction." aim.x = x aim.y = y def inside(head): "Return True if head inside boundaries." return -200 < head.x < 190 and -200 < head.y < 190 def move(): "Move snake forward one segment." head = snake[-1].copy()
# IMPORTAÇÃO DE MÓDULOS from freegames import square, vector from random import randrange from turtle import * # DEFINIÇÃO DA MIRA DA COBRA mira = vector(0, -10) def ponto1(x, y): mira.y = y mira.x = x # DEFINIÇÃO DO TAMANHO DA COBRA E DA TELA cobra = [vector(10, 0)] def ponto2(head): return -800 < head.x < 400 and -800 < head.y < 400 # DEFINIÇÃO DA FORMA E TAMANHO DA COMIDA, RANDOMIZAÇÃO DO SPAWN TAMBÉM comida = vector(0, 0) def ponto3(): head = cobra[-1].copy() head.move(mira) if not ponto2(head) or head in cobra:
def atira(player): tiro = vector(player.x, player.y) print(player.x, player.y) tiros.append(tiro + 1)
def move(): #apaga a ultima posição: escrever.undo() #atualiza o placar: escrever.write(placar['score']) #limpa a tela: clear() #movimenta o player: if valido(player + direção): player.move(direção) #pega o idice do mapa do player: index = delocamento(player) #apaga a fruta e atualiza o placar: if mapa[index] == 1: mapa[index] = 5 placar['score'] += 5 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 quadrado(x, y) up() goto(player.x + 10, player.y + 10) dot(20, 'yellow') if mapa[index] == 2: mapa[index] = 5 placar['score'] += 1 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 quadrado(x, y) up() goto(player.x + 10, player.y + 10) dot(20, 'yellow') if mapa[index] == 3: mapa[index] = 5 placar['score'] += 10 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 quadrado(x, y) up() goto(player.x + 10, player.y + 10) dot(20, 'yellow') #movimentação das balas for tiro in tiros: if valido(tiro + direção): tiro.move(direção) goto(tiro.x + 10, tiro.y + 10) dot(9, 'red') #movimentação dos inimigos: for pontos, course in inimigos: if valido(pontos + course): pontos.move(course) else: options = [ vector(velocidade_inimigo, 0), vector(-velocidade_inimigo, 0), vector(0, velocidade_inimigo), vector(0, -velocidade_inimigo), ] plan = choice(options) course.x = plan.x course.y = plan.y up() goto(pontos.x + 10, pontos.y + 10) dot(20, 'red') update() for pontos, course in inimigos: if abs(player - pontos) < 20: placar['score'] -= 4 for tiro in tiros: if abs(pontos - tiro) < 20: placar['score'] += 1 inimigos.pop() tiros.pop() if len(inimigos) == 0: os.system('cls' if os.name == 'nt' else 'clear') exit(9) congratulation() ontimer(move, 100) #movimentação dos inimigos2: for pontos, course in inimigos2: if valido(pontos + course): pontos.move(course) else: options = [ vector(velocidade_inimigo2, 0), vector(-velocidade_inimigo2, 0), vector(0, velocidade_inimigo2), vector(0, -velocidade_inimigo2), ] plan2 = choice(options) course.x = plan2.x course.y = plan2.y up() goto(pontos.x + 10, pontos.y + 10) dot(6, 'orange') update() for pontos, course in inimigos2: if abs(player - pontos) < 20: placar['score'] += 5 adiciona() for tiro in tiros: if abs(pontos - tiro) < 20: inimigos2.pop() tiros.pop()
import random import turtle import time import os #veocidades dos personagens: velocidade_player = 10 velocidade_inimigo = 5 velocidade_inimigo2 = 7 velocidade_inimigo3 = 10 #coordenada x y: placar = {'score': 0} caminho = Turtle(visible=False) escrever = Turtle(visible=False) direção = vector(5, 0) tiros = [] #posisão do player: pos = [-200, -180] player = vector(pos[0], pos[1]) #posisão do inimigo: inimigos = [ [vector(0, -80), vector(velocidade_inimigo, 0)], [vector(-200, 100), vector(0, velocidade_inimigo)], [vector(160, -20), vector(0, -velocidade_inimigo)], [vector(100, 160), vector(-velocidade_inimigo, 0)], ] inimigos2 = [ [vector(-100, -100), vector(0, velocidade_inimigo2)],
#this is a puzzle game made by pabitra ghosh from random import * from turtle import * from freegames import floor, vector tiles = {} neighbors = [ vector(100, 0), vector(-100, 0), vector(0, 100), vector(0, -100), ] def load(): "Load tiles and scramble." count = 1 for y in range(-200, 200, 100): for x in range(-200, 200, 100): mark = vector(x, y) tiles[mark] = count count += 1 tiles[mark] = None for count in range(1000): neighbor = choice(neighbors) spot = mark + neighbor if spot in tiles:
def move(): #kretnja pacmana i duhova - samostalno writer.undo() writer.write(stanje['rezultat']) clear() for ve in pacman: index = offset(ve[0]) if polje[index] == 1: polje[index] = 2 stanje['rezultat'] += 1 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 square(x, y) elif polje==0: print("POBJEDA, ovo je kraj igre!") for point, course in pacman: if valid(point + course): point.move(course) else: options = [ vector(5, 0), vector(-5, 0), vector(0, 5), vector(0, -5), ] plan = choice(options) course.x = plan.x course.y = plan.y up() goto(point.x + 10, point.y + 10) dot(20, 'yellow') for point, course in duh: for point2, course2 in pacman: opposite=point.y-point2.y adjacent=point.x-point2.x try: angle = atan(adjacent/opposite) if point2.x < point.x: backward(100) except ZeroDivisionError: angle = 0 if valid(point + course): point.move(course) else: options = [ vector(5, 0), vector(-5, 0), vector(0, 5), vector(0, -5), ] plan = choice(options) course.x = plan.x course.y = plan.y up() goto(point.x + 10, point.y + 10) dot(20, 'white') update() for point, course in duh: if abs(ve[0] - point) < 20: print("UDAR, izgubio sam.") f = open("Rezultat.txt", "a+") f.write("\ns: " + str(stanje['rezultat'])) bye() return ontimer(move, 100)
def tap(x, y): "Move bird up in response to screen tap." up = vector(0, 30) bird.move(up)
import random import turtle from random import randrange from turtle import * from freegames import vector wn = turtle.Screen() wn.bgcolor("black") wn.title("cannon game") ball = vector(-200, -200) speed = vector(0, 0) targets = [] list = ['orange', 'yellow', 'gold'] def tap(x, y): " respond to screen tap" if not inside(ball): ball.x = -199 ball.y = -199 speed.x = (x + 250) / 25 speed.y = (y + 250) / 25 def inside(xy): "return true if xy witin screen" return -200 < xy.x < 200 and -200 < xy.x < 200 def draw(): "draw ball and targets"
"""Flappy, game inspired by Flappy Bird. Exercises 1. Keep score. 2. Vary the speed. 3. Vary the size of the balls. 4. Allow the bird to move forward and back. """ from random import * from turtle import * from freegames import vector bird = vector(0, 0) balls = [] setup(420, 420, 370, 0) hideturtle() def tap(x, y): "Move bird up in response to screen tap." up = vector(0, 30) bird.move(up) def inside(point): "Return True if point on screen." return -200 < point.x < 200 and -200 < point.y < 200
def tap(x, y): #새의 위치를 위로 이동시키는 함수 "Move bird up in response to screen tap." up = vector(0, 30) bird.move(up)
"""Flappy, game inspired by Flappy Bird. Exercises #연습문제 1. Keep score. #1. 점수를 계속 보여주게 하자 2. Vary the speed. #2. 속도를 다양하게 해보자 3. Vary the size of the balls. #3. 공의 크기를 다양하게 해보자 4. Allow the bird to move forward and back. #4. 새가 앞 뒤로 움직일 수 있게 해보자 """ from random import * from turtle import * from freegames import vector bird = vector(0, 0) #새의 위치 초기 설정 balls = [] def tap(x, y): #새의 위치를 위로 이동시키는 함수 "Move bird up in response to screen tap." up = vector(0, 30) bird.move(up) def inside(point): #점이 스크린에 있으면 참을 반환 "Return True if point on screen." return -200 < point.x < 200 and -200 < point.y < 200 def draw(alive): #새의 생사에 따라 색깔 변경
def change(x, y): "Change pacman aim if valid." if valid(pacman + vector(x, y)): aim.x = x aim.y = y
def change(x, y): #mjenjanje pacman-a s obzirom na tipke if valid(pacman2 + vector(x, y)): aim.x = x aim.y = y
"""Cannon, hitting targets with projectiles. Exercises 1. Keep score by counting target hits. 2. Vary the effect of gravity. 3. Apply gravity to the targets. 4. Change the speed of the ball. """ from random import randrange from turtle import * from freegames import vector ball = vector(-200, -200) speed = vector(0, 0) targets = [] def tap(x, y): "Respond to screen tap." if not inside(ball): ball.x = -199 ball.y = -199 speed.x = (x + 200) / 25 speed.y = (y + 200) / 25 def inside(xy): "Return True if xy within screen." return -200 < xy.x < 200 and -200 < xy.y < 200
def tap(self): "Move bird up in response to screen tap." up = vector(0, self.tapY_mov) self.bird.move(up)
1. Speed up tile flash rate. 2. Add more tiles. """ from random import choice from time import sleep from turtle import * from freegames import floor, square, vector import time pattern = [] guesses = [] tiles = { vector(0, 0): ('red', 'dark red'), vector(0, -200): ('blue', 'dark blue'), vector(-200, 0): ('green', 'dark green'), vector(-200, -200): ('yellow', 'khaki'), } def grid(): "Draw grid of tiles." square(0, 0, 200, 'dark red') square(0, -200, 200, 'dark blue') square(-200, 0, 200, 'dark green') square(-200, -200, 200, 'khaki') update() def flash(tile): "Flash tile in grid."
def move(): "Move pacman and all ghosts." writer.undo() writer.write(state['score']) clear() if valid(pacman + aim): pacman.move(aim) index = offset(pacman) if tiles[index] == 1: tiles[index] = 2 state['score'] += 1 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 square(x, y) up() goto(pacman.x + 10, pacman.y + 10) dot(20, 'yellow') #statements for point, course in ghosts: if valid(point + course): point.move(course) else: options = [ vector(5, 0), vector(-5, 0), vector(0, 5), vector(0, -5), ] plan = choice(options) course.x = plan.x course.y = plan.y up() goto(point.x + 10, point.y + 10) dot(20, 'red') update() for point, course in ghosts: if abs(pacman - point) < 20: return ontimer(move, 100)
def adiciona(): aux = [[vector(-160, -180), vector(velocidade_inimigo, 0)], [vector(160, 160), vector(velocidade_inimigo, 0)]] inimigos.append(choice(aux))
def __init__(self, x, y): self.position = vector(x, y)
def change(x, y): if valido(player + vector(x, y)): direção.x = x direção.y = y
def __init__(self, x=0, y=0): self.head = Head(x, y) self.body = [vector(10, 0)] self.aim = vector(0*self.SPEED, -10*self.SPEED) self.status = 'LIVE'
"""Tron, classic arcade game. Exercises 1. Make the tron players faster/slower. 2. Stop a tron player from running into itself. 3. Allow the tron player to go around the edge of the screen. 4. How would you create a computer player? """ from turtle import * from freegames import square, vector p1xy = vector(-100, 0) p1aim = vector(4, 0) p1body = set() p2xy = vector(100, 0) p2aim = vector(-4, 0) p2body = set() def inside(head): "Return True if head inside screen." return -200 < head.x < 200 and -200 < head.y < 200 def draw(): "Advance players and draw game."
Exercises # 연습문제 1. Track a score by the number of tile moves. # 1. 타일 이동 횟수로 점수를 획득합니다. 2. Permit diagonal squares as neighbors. # 2. 대각선을 이동을 허용하십시오. 3. Respond to arrow keys instead of mouse clicks. # 3. 마우스 클릭 대신 화살표 키를 이용해보세요. 4. Make the grid bigger. # 4. 숫자판과 사용자 인터페이스를 더 크게 만듭니다. """ from random import * # random 모듈을 불러온다 from turtle import * # turtle 모듈을 불러온다 from freegames import floor, vector # freegames 모듈에서 floor, vector함수를 불러온다. tiles = {} # 타일들을 위한 배열 선언 neighbors = [ # 인접 타일 관리를 위한 배열 선언 vector(100, 0), # 오른쪽 인접 타일 vector(-100, 0), # 왼쪽 인접 타일 vector(0, 100), # 위쪽 인접 타일 vector(0, -100), # 아래쪽 인접 타일 ] def load(): "Load tiles and scramble." # 타일들을 불러오는 함수 count = 1 for y in range(-200, 200, 100): # 타일 바깥의 윤곽선 그리기 for x in range(-200, 200, 100): mark = vector(x, y) tiles[mark] = count count += 1
3. Make the ball leave a trail. 4. Change the ball color based on position. Hint: colormode(255); color(0, 100, 200) """ from random import * from turtle import * from freegames import vector def value(): "Randomly generate value between (-5, -3) or (3, 5)." return (3 + random() * 2) * choice([1, -1]) ball = vector(0, 0) aim = vector(value(), value()) def draw(): "Move ball and draw game." ball.move(aim) x = ball.x y = ball.y if x < -200 or x > 200: aim.x = -aim.x if y < -200 or y > 200: aim.y = -aim.y
"""Snake, classic arcade game. Excercises 1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. """ from turtle import * from random import randrange from freegames import square, vector s = 10 food = vector(0, 0) snake = [vector(s, 0)] aim = vector(0, -s) cnt = vector(0, 0) def change(x, y): "Change snake direction." if (aim.x * x < 0 or aim.y * y < 0): print("无效的方向改变") return aim.x = x aim.y = y def inside(head): "Return True if head inside boundaries." return -200 < head.x < 190 and -200 < head.y < 190
"""Snake, classic arcade game. Excercises 1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. """ from random import randrange from turtle import * from freegames import square, vector s = 10 food = vector(0, 0) snake = [vector(s, 0)] aim = vector(0, -s) times = vector(200, 0) delta_speed = 25 def change(x, y): "Change snake direction." if (aim.x * x < 0 or aim.y * y < 0): print("后退减速") times.x += delta_speed return if (aim.x == x and aim.y == y): print("前进加速") times.x = max(10, times.x - delta_speed) aim.x = x
"""Ant, simple animation demo. Exercises 1. Wrap ant around screen boundaries. 2. Make the ant leave a trail. 3. Change the ant color based on position. Hint: colormode(255); color(0, 100, 200) """ from random import * from turtle import * from freegames import vector ant = vector(0, 0) aim = vector(2, 0) def wrap(value): "Wrap value around -200 and 200." return value # TODO def draw(): "Move ant and draw screen." ant.move(aim) ant.x = wrap(ant.x) ant.y = wrap(ant.y) aim.move(random() - 0.5) aim.rotate(random() * 10 - 5)
1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. 1. Como você deixa a cobra mais rápida ou mais lenta? FEITO 2. Como você pode fazer a cobra contornar as bordas? 3. Como você moveria a comida? 4. Mude a cobra para responder às teclas de seta FEITO """ from turtle import * from random import randrange from freegames import square, vector food = vector(0, 0) #posição inicial da comida snake = [vector(10, 0)]#posição inicial da cobra aim = vector(0,-20) # velocidade/direção da cobra def change(x, y): "Change snake direction."#"Mudar a direção da cobra." aim.x = x aim.y = y def inside(head): "Return True if head inside boundaries."#"Retorne True se a cabeça estiver dentro dos limites." return -200 < head.x < 190 and -200 < head.y < 190 def move(): "Move snake forward one segment." #Mova a cobra um segmento para frente head = snake[-1].copy()
def tap(x, y): "Move bird up in response to screen tap." up = vector(0, 50) # 0,30 це відстань на яку ми підстрибуємо bird.move(up)
"""Snake, classic arcade game. Excercises 1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. """ from turtle import * from random import randrange from freegames import square, vector food = vector(0, 0) snake = [vector(10, 0)] aim = vector(0, -10) def change(x, y): "Change snake direction." aim.x = x aim.y = y def inside(head): "Return True if head inside boundaries." return -200 < head.x < 190 and -200 < head.y < 190 def move(): "Move snake forward one segment." head = snake[-1].copy()
# підключаємо бібліотеки from turtle import * # черепашка from random import randrange # рандом from freegames import square, vector # freegames - вектори food = vector(0, 0) # 0, 0 початкові координати snake = [vector(20, 5)] # 20, 5 початкові координати змійки aim = vector(0, -15) # 0, -15 початковий напрям змійки def change(x, y): aim.x = x aim.y = y def inside(head): # Перевірка на те чи ми знаходимось всередині карти # Границі карти в пікселях, можна міняти return -200 < head.x < 190 and -200 < head.y < 190 def move(): # рух змійки head = snake[-1].copy() head.move(aim) # Створюємо червоний квадрат перед змійкою, якщо вона вилазить за межі карти if not inside(head) or head in snake: square(head.x, head.y, 9, 'red') update() return snake.append(head) # рандомна поява їжі
from random import choice from turtle import * from freegames import floor, vector state = {'score': 0} path = Turtle(visible=False) writer = Turtle(visible=False) aim = vector(5, 0) pacman = vector(-40, -80) ghosts = [ [vector(-180, 160), vector(5, 0)], [vector(-180, -160), vector(0, 5)], [vector(100, 160), vector(0, -5)], [vector(100, -160), vector(-5, 0)], ] tiles = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Exercises 1. Speed up tile flash rate. 2. Add more tiles. """ from random import choice from time import sleep from turtle import * from freegames import floor, square, vector pattern = [] guesses = [] tiles = { vector(0, 0): ('red', 'dark red'), vector(0, -200): ('blue', 'dark blue'), vector(-200, 0): ('green', 'dark green'), vector(-200, -200): ('yellow', 'khaki'), } def grid(): "Draw grid of tiles." square(0, 0, 200, 'dark red') square(0, -200, 200, 'dark blue') square(-200, 0, 200, 'dark green') square(-200, -200, 200, 'khaki') update() def flash(tile): "Flash tile in grid."
4. Change the size of the paddles. 5. Change how the ball bounces off walls. 6. How would you add a computer player? 6. Add a second ball. """ from random import choice, random from turtle import * from freegames import vector def value(): "Randomly generate value between (-5, -3) or (3, 5)." return (3 + random() * 2) * choice([1, -1]) ball = vector(0, 0) aim = vector(value(), value()) state = {1: 0, 2: 0} def move(player, change): "Move player position by change." state[player] += change def rectangle(x, y, width, height): "Draw rectangle at (x, y) with given width and height." up() goto(x, y) down() begin_fill() for count in range(2): forward(width)
def change(x, y): "Change pacman aim if valid." if valid(pacman + vector(x, y)): aim.x = x aim.y = y