grantjenks / free-python-games Goto Github PK
View Code? Open in Web Editor NEWFree Python Games
Home Page: http://www.grantjenks.com/docs/freegames/
License: Other
Free Python Games
Home Page: http://www.grantjenks.com/docs/freegames/
License: Other
Reminder: Work with Rick Schertle to develop curriculum.
If others are interested in developing a curriculum then please comment below.
Hi.
I'm a professor and I'm starting to tutor students to implement OOP version games.
(Recently, we receive a donation to this initiative - in pt-br)
We not intend to change the current files, but just add new files (rewriting some games) in this programming paradigm.
So FPG would can be used in OOP courses, too.
A initial idea is add a new folder, called oop, where these new files will live.
So, if you want copy the snake game in a oop approach, you just type
$ python3 -m freegames copy oop.snake
$ python3 snake.py
What do you think about? Some comment? Some preference for what game we can start?
Link to source code from documentation, pretty easy to do with sphinx.
Move docs/demo.py to freegames/demo.py and improve source.
Show how to run (maybe auto-install packages using pip) in docs.
Add Simulation: Solar System
Using Turtle, draw the horizontal line illusion like shown here: http://www.illusions.org/dp/1-2.htm
Added red dot.
Red dot is trash.
If the snake eat trash, it will be reduced in length by one.
If snake meet trash when len(snake) == 1, the game ends
And If the game is over, IDLE will print out 'Game End'.
This is code.
The word "exercises" in snake.py is misspelled as "excercises'
(This is my very first time "contributing" to GitHub. I'm fairly new to programming and I decided to start with Python. I'm very lucky to have discovered freegames!)
It would be wonderful if each student can to read the documentation (in a first moment, and the source-code comments in a second moment) in your own idiom, not only English.
import mockturtle
it says it aint a import
I tried to run the life game via freegames play life
. When I click close button of the game window. I got Exception in Tkinter callback
.
> freegames play life
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Liu.D.H\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "C:\Users\Liu.D.H\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 861, in callit
func(*args)
File "C:\Users\Liu.D.H\AppData\Local\Programs\Python\Python311\Lib\site-packages\freegames\life.py", line 61, in draw
ontimer(draw, 100)
File "<string>", line 5, in ontimer
turtle.Terminator
Estimate n-digits numbers randomly created.
Each digit is not repeated. (123 -> O / 899 -> X)
Strike: A correct number in a right position.
Ball: A correct number in a different position.
See screenshot.
Implement Battleship against the computer.
Implement hangman with an AI.
Instead of using "hangman" which is politically incorrect, use Ascii Art and make the picture disappear.
Pretty shapes in joy at https://github.com/fossunited/joy
It may be just me, but I started building in a "solvable" check for the tiles generated. To boil it down, I used two rules:
If neither of these rules are true, the puzzle is unsolvable.
The problem is, when I put this logic into place, the game generated puzzles that were unsolvable 100% of the time.
I was able to fix the problem by taking the values (numbers) of tiles variable and shuffling that, then rejoining the keys and values of the tiles dictionary. Once this was done, the game generates solvable puzzles as often as not.
It may be obvious by now that I have no idea what I'm doing haha but I'm trying to learn!
Is it just me, or are the puzzles always unsolvable, and why might this be? I'm staring at the original code, but I have no idea how 1-15 is arrived upon, as the ranges involved are much larger, such as 100, -200, 100, etc...
I'm not sure if it'd be worth doing a pull request for the 'check solvable' logic when done; I'm sure many other people who actually know what they're doing are involved in this project. Maybe it could be described as a suggested exercise at the beginning of the file?
This repository has several board games, made with pure Python or PyZero: https://github.com/rg-software/board-games
Maybe some would can be ported to Free Python Games.
Lots of good ideas at: https://github.com/coding-horror/basic-computer-games
See: https://en.wikipedia.org/wiki/Minesweeper_(video_game)
Prototype:
"""Minesweeper Game
Just playing around. The code below is not well tested.
"""
import random
import collections
random.seed(1)
size = 5
bombs = collections.defaultdict(int)
counts = collections.defaultdict(int)
display = collections.defaultdict(lambda: 'X')
neighbors = sorted(set((i, j) for i in range(size) for j in range(size)) - {(0, 0)})
# Initialize
for x in range(size):
for y in range(size):
bombs[x, y] = 0
counts[x, y] = 0
display[x, y] = '?'
# Set bombs
for _ in range(3):
x = random.randrange(size)
y = random.randrange(size)
bombs[x, y] = 1
# Calculate counts
for x in range(size):
for y in range(size):
total = 0
for i in [-1, 0, 1]:
for j in [-1, 0, 1]:
total += bombs[x + i, y + j]
counts[x, y] = total
def show(grid):
for x in range(size):
for y in range(size):
print(grid[x, y], end=', ')
print()
print('Bombs:')
show(bombs)
print('Counts:')
show(counts)
alive = True
def reveal(x, y):
"""Update display and return True/False for alive status.
"""
if bombs[x, y]:
return False
display[x, y] = counts[x, y]
if counts[x, y]:
return True
zeros = [ (x, y) ]
while zeros:
x, y = zeros.pop()
if not ((0 <= x < size) and (0 <= y < size)):
continue
if counts[x, y] == 0:
display[x, y] = 0
for i in (-1, 0, 1):
for j in (-1, 0, 1):
if i == j == 0:
continue
offset_x = x + i
offset_y = y + j
seen = display[offset_x, offset_y] != '?'
if counts[offset_x, offset_y] == 0 and not seen:
zeros.append( (offset_x, offset_y) )
return True
while alive:
show(display)
x = int(input('row: '))
y = int(input('column: '))
alive = reveal(x, y)
if not alive or not any(spot == '?' for spot in display.values()):
break
if alive:
print('Congratulations! You win.')
else:
print('Sorry, you failed.')
See prototype at https://code.activestate.com/recipes/578808-python-game-of-life/
Game idea for mad libs from https://nedbatchelder.com//blog/202011/mad_libs.html
Game idea: solitaire
The game named guess
asks you to guess a number but when I tried to run the game, I'm getting the number beforehand which doesn't justify the game. I've attached the screenshot where I'm able to guess the number in my first attempt because of this. Kindly look into this and do the needful. Kindly mark it as a bug.
Also, I'm trying to put a solution further & raised a CR for this but FYI, LINE 17 should be marked as a comment.
Let me know if this is just me....
I have Python 3.6.7 and tkinter was not install initially (I'm using ubuntu)
had to run
sudo apt-get install python3-tk
to get tinkter working
below was my first attempt of running after
user@computer:~/programming/python/free-python-games$ python3 -m freegames.snake
Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/lcc/programming/python/free-python-games/freegames/snake.py", line 12, in
from turtle import *
File "/usr/lib/python3.6/turtle.py", line 107, in
import tkinter as TK
ModuleNotFoundError: No module named 'tkinter'
We need some documentation about build and run the docs.
See: https://en.wikipedia.org/wiki/Tetris
Prototype:
"""Game of Tetris for Liftoff Interview
Written by Grant Jenks
Copyright 2019
"""
import atexit
import collections
import itertools
import random
import sqlite3
import threading
import time
import console
original_terminal_state = console.get_terminal_mode()
atexit.register(console.set_terminal_mode, original_terminal_state)
class Game:
"Game state for Tetris."
def __init__(self, width, height, seed=None):
self.random = random.Random(seed)
self.width = width
self.height = height
self.board = collections.defaultdict(lambda: '#')
for x in range(width):
for y in range(height):
self.board[x, y] = ' '
self.active = True
self.speed = 20
self.next_letter = self.random.choice('IJLOSTZ')
self.piece = self.next_piece()
self.score = 0
self.stash = None
def draw(self):
"Draw game state."
print('Score:', self.score, end='\r\n')
print('Level:', self.score // 4 + 1, end='\r\n')
print('Next piece:', self.next_letter, end='\r\n')
print('Stash piece:', 'no' if self.stash is None else 'yes', end='\r\n')
print('*' * (self.width + 2), end='\r\n')
for y in range(self.height):
print('|', end='')
for x in range(self.width):
if (x, y) in self.piece:
print('@', end='')
else:
print(self.board[x, y], end='')
print('|', end='\r\n')
print('*' * (self.width + 2), end='\r\n')
def next_piece(self):
"Create a new piece, on collision set active to False."
letter = self.next_letter
self.next_letter = self.random.choice('IJLOSTZ')
if letter == 'I':
piece = {(0, 0), (0, 1), (0, 2), (0, 3)}
elif letter == 'J':
piece = {(1, 0), (1, 1), (1, 2), (0, 2)}
elif letter == 'L':
piece = {(0, 0), (0, 1), (0, 2), (1, 2)}
elif letter == 'O':
piece = {(0, 0), (0, 1), (1, 0), (1, 1)}
elif letter == 'S':
piece = {(0, 1), (1, 0), (1, 1), (2, 0)}
elif letter == 'T':
piece = {(0, 0), (1, 0), (2, 0), (1, 1)}
else:
assert letter == 'Z'
piece = {(0, 0), (1, 0), (1, 1), (2, 1)}
offset = self.width // 2 - 1
piece = {(x + offset, y) for x, y in piece}
if self.collide(piece):
self.end()
return piece
def end(self):
self.active = False
print('Game over! Press any key to quit.', end='\r\n')
def tick(self, mark):
"Notify the game of a clock tick."
if mark % self.speed == 0:
moved = self.move_piece(0, 1)
if not moved:
for x, y in self.piece:
self.board[x, y] = '#'
self.collapse()
self.piece = self.next_piece()
self.draw()
def collapse(self):
"Collapse full lines."
y = self.height - 1
while y >= 0:
full_line = all(self.board[x, y] == '#' for x in range(self.width))
if full_line:
z = y
while z > 0:
for x in range(self.width):
self.board[x, z] = self.board[x, z - 1]
z -= 1
for x in range(self.width):
self.board[x, 0] = ' '
self.score += 1
if self.score % 4 == 0:
self.speed -= 1
else:
y -= 1
def collide(self, piece):
"Check whether piece collides with others on board."
return any(self.board[x, y] != ' ' for x, y in piece)
def move_piece(self, x, y):
"Move piece by delta x and y."
new_piece = {(a + x, y + b) for a, b in self.piece}
if self.collide(new_piece):
return False
self.piece = new_piece
return True
def rotate_piece(self):
"Rotate piece."
min_x = min(x for x, y in self.piece)
max_x = max(x for x, y in self.piece)
diff_x = max_x - min_x
min_y = min(y for x, y in self.piece)
max_y = max(y for x, y in self.piece)
diff_y = max_y - min_y
size = max(diff_x, diff_y)
new_piece = set()
for x, y in self.piece:
pair = (min_x + size) - (y - min_y), min_y + (x - min_x)
new_piece.add(pair)
if self.collide(new_piece):
return False
self.piece = new_piece
return True
def move(self, key):
"Update game state based on key press."
if key == 'left':
moved = self.move_piece(-1, 0)
elif key == 'right':
moved = self.move_piece(1, 0)
elif key == 'down':
moved = self.move_piece(0, 1)
elif key == 'up':
moved = self.rotate_piece()
elif key == 'swap':
if self.stash is None:
self.stash = self.piece
self.piece = self.next_piece()
else:
self.piece, self.stash = self.stash, self.piece
if self.collide(self.piece):
self.end()
moved = True
else:
assert key == 'space'
moved = self.move_piece(0, 1)
while moved:
moved = self.move_piece(0, 1)
moved = True
if moved:
self.draw()
def draw_loop(game):
"""Draw loop.
Handle console drawing in a separate thread.
"""
game.draw()
counter = itertools.count(start=1)
while game.active:
mark = next(counter)
game.tick(mark)
time.sleep(0.1)
def input_loop(game):
"""Input loop.
Handle keyboard input in a separate thread.
"""
while game.active:
key = console.get_input()
if key is None:
continue
elif key == 'quit':
game.active = False
else:
assert key in ('left', 'down', 'right', 'up', 'space', 'swap')
game.move(key)
console.set_terminal_mode(original_terminal_state)
print('Enter your name for leaderboard (blank to ignore):')
name = input()
if name:
con = sqlite3.connect('tetris.sqlite3', isolation_level=None)
con.execute('CREATE TABLE IF NOT EXISTS Leaderboard (name, score)')
con.execute('INSERT INTO Leaderboard VALUES (?, ?)', (name, game.score))
scores = con.execute('SELECT * FROM Leaderboard ORDER BY score DESC LIMIT 10')
print('{0:<16} | {1:<16}'.format('Name', 'Score'))
for pair in scores:
print('{0:<16} | {1:<16}'.format(*pair))
def main():
"Main entry-point for Tetris."
game = Game(10, 10)
draw_thread = threading.Thread(target=draw_loop, args=(game,))
input_thread = threading.Thread(target=input_loop, args=(game,))
draw_thread.start()
input_thread.start()
draw_thread.join()
input_thread.join()
if __name__ == '__main__':
main()
Feedback from Paul Craven of programarcadegames.com: add more comments to games. Lots of comments really help students.
Getting this error:
stash: <class 'TypeError'>: setup() takes from 1 to 3 positional arguments but 5 were given
When I type python3 -m freegames.snake
Hello i am interested in making your code Windows 10 friendly, it would require me to go over the code and make some changes, to make it compatible with pyinstaller, after that i will create a Windows EXE installer, and sign the exe's with my certificate.
You do not have the merge my fork but instead just include the installer in your release tags.
I look forward to hearing back from you! :D
See step_by_step repo for an initial implementation.
Annotate with comments:
# >>> 1
def count(iterable):
return sum(1 for val in iterable)
# <<<
# >>> 2
total = count(values)
# <<<
def count(iterable): # 1 Function start.
total = 0 # 2 Block.
for val in iterable: # 3 Loop start.
total += 1 # 4 Block.
return total # 5 Function end.
# >>> 6v1
foreground = (0, 0, 0)
# <<<
# >>> 6v2
foreground = (255, 0, 0)
# <<<
When user completes game successfully, display message displaying number of guesses it took to complete.
Include tests.
Message will be:
(if guesses > 1)
Congratulations! You guessed the right answer:[value]
It took you [number of guesses] guesses!
(if guesses == 1)
Congratulations! You guessed the right answer:[value]
It took you 1 guess!
I have a flappy bird app running. However, I am trying to run inside a Tkinter, but I am not able to. Is there a way to insert the game inside Tkinter Canvas.
When a tile with 'not hide' state is tapped again, No. of that tile appears on the image.
It seems better to resolve this problem.
I am a student that has experience in programming but not GitHub. So I want to start with something simple. Is it ok for me to contribute to your project with the game battleships
Hello,
I'm a computer science student and I have to contribute to an open source project for a course about the open source.
I've found this repository and find it really cool to help new programmers to learn python.
Is it possible to contribute by adding the game flappy bird ?
I'll try to keep it really simple so that every newcomers can understand the core of the game quickly.
Thanks in advance
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.