العاب بايثون مجانية مع واجهه رسومية
تعلم لغة Python من خلال دمج المرح لممارسة ألعاب خفيه وبسيطه مثل لعبة حرب الفضاء و الذاكرة. تتراوح الألعاب من الألعاب الأساسية (التي توضح المفاهيم الأساسية في Python) إلى بعض الألعاب المتقدمة التي توضح مفاهيم الفئات العليا في Python جنبًا إلى جنب مع منطق الفيزياء المطلوب لصنع مثل هذه الألعاب, وهو جانب مهم جداً لفهمه خلال رحلتك التعليمية في البرمجة وصنع برامجك الخاصة في عالم برمجة بايثون.
هناك إجمالي 8 ألعاب مرتبة من الأسهل الى الأكثر تعقيداً ، آخر لعبة تسمى حرب الفضاء أو “Asteroids” لعبة رائعة حقًا للنظر إليها ومراجعة الكود البرمجي الخاص بها.
كيف تقوم بتجربة الكود
ان كنت لاتملك محرر اكواد بايثون تستطيع زيارة الموضوع لتالي, او تستطيع استخدام موقع CodeSkulptor ببساطة انسخ كل كود اللعبة والصقه في محرر CodeSkulptor. ثم انقر فوق الزر “تشغيل” وستبدأ اللعبة
لعبة حجره, ورقه, مقص
# Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
import random
import simplegui
# helper functions
def name_to_number(name):
# convert name to number using if/elif/else
# don't forget to return the result!
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
print "Error: Not a valid name"
#----------------------------------------------------------
#----------------------------------------------------------
def number_to_name(number):
# convert number to a name using if/elif/else
# don't forget to return the result!
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "Error: Not a valid number"
#----------------------------------------------------------
#----------------------------------------------------------
def rpsls(player_choice):
print "------------"
print "------------"
print "Player chooses " + player_choice
player_number = name_to_number(player_choice)
comp_number = random.randrange(0,5)
comp_choice = number_to_name(comp_number)
print "Computer chooses " + comp_choice
diff = (comp_number - player_number) % 5
if diff == 1 or diff == 2:
print "Computer Wins"
elif diff == 3 or diff == 4:
print "Player Wins"
else:
print "Player and computer tie!"
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
# Event Handlers
def get_input(inp):
if (inp == "rock" or inp == "paper" or inp == "lizard" or
inp == "Spock" or inp == "scissors"):
rpsls(inp)
else:
print "Error: Invalid Input"
# Creating a Frame
frame = simplegui.create_frame("Rock-paper-scissors-lizard-Spock",200,200)
# Registering Handlers
frame.add_input("Enter your choice: ", get_input,200)
# Starting the Frame
frame.start()
"""
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
"""
# always remember to check your completed program against the grading rubric
تخمين الرقم
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import math
import simplegui
#------------------------------------------
# declaring global variables
secret_number = 0
num_range = 100
remaining_guesses = 0
#------------------------------------------
# helper function to start and restart the game
def new_game():
print "----------------------------------------"
print "----------------------------------------"
print "New game. Range is from 0 to", num_range
global secret_number, remaining_guesses
secret_number = random.randrange(0, num_range)
remaining_guesses = int( math.ceil(math.log(num_range, 2)) )
print "Total Guesses:", remaining_guesses
#------------------------------------------
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global num_range
num_range = 100
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global num_range
num_range = 1000
new_game()
def reset():
new_game()
def input_guess(guess):
global remaining_guesses
guess = int(guess)
print "Guess was", guess
if guess < secret_number:
print "Higher!"
elif guess > secret_number:
print "Lower!"
else:
print "Correct!"
new_game()
return
remaining_guesses -= 1
print ""
print "Number of remaining guesses is :", remaining_guesses
if remaining_guesses == 0:
print "You ran out of guesses :( The secret number was", secret_number
new_game()
#------------------------------------------
# create frame
frame = simplegui.create_frame("Guess the Number", 200, 200)
#------------------------------------------
# register event handlers for control elements and start frame
frame.add_button("Range is [0, 100)", range100, 200)
frame.add_button("Range is [0, 1000)", range1000, 200)
frame.add_input("Enter a guess", input_guess, 200)
frame.add_button("New Game", reset, 200)
#------------------------------------------
# call new_game
new_game()
#------------------------------------------
# starting the frame
frame.start()
#------------------------------------------
# always remember to check your completed program against the grading rubric
لعبة الساعة
# template for "Stopwatch: The Game"
#-------------------------------------------------
#-------------------------------------------------
# global state
import simplegui
# define global variables
ticks = 0
total_stops = 0
correct_stops = 0
timer_stopped = True
#-------------------------------------------------
#-------------------------------------------------
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
# one tenth of a second
d = t % 10
# total seconds
seconds = t // 10
a = seconds // 60
bc = seconds % 60
c = bc % 10
b = bc // 10
result = str(a) + ":" + str(b) + str(c) + "." + str(d)
return result
#-------------------------------------------------
#-------------------------------------------------
# define event handlers for buttons; "Start", "Stop", "Reset"
def start():
global timer_stopped
timer.start()
timer_stopped = False
def stop():
global timer_stopped
if not timer_stopped:
timer.stop()
global total_stops, correct_stops
if ticks % 10 == 0:
correct_stops += 1
total_stops += 1
timer_stopped = True
def reset():
global ticks, correct_stops, total_stops, timer_stopped
ticks = 0
correct_stops = 0
total_stops = 0
timer_stopped = True
timer.stop()
#-------------------------------------------------
#-------------------------------------------------
# define event handler for timer with 0.1 sec interval
def increment_ticks():
global ticks
ticks += 1
# define draw handler
def draw(canvas):
canvas.draw_text(format(ticks), [75, 100], 40, "Green")
canvas.draw_text(str(correct_stops) + "/" + str(total_stops), [270,20], 20, "Red")
#-------------------------------------------------
#-------------------------------------------------
# create frame
frame = simplegui.create_frame("Stop Watch: The Game", 300, 200)
timer = simplegui.create_timer(100, increment_ticks)
#-------------------------------------------------
#-------------------------------------------------
# register event handlers
frame.set_draw_handler(draw)
frame.add_button("Start", start, 100)
frame.add_button("Stop", stop, 100)
frame.add_button("Reset", reset, 100)
#-------------------------------------------------
#-------------------------------------------------
# start frame
frame.start()
#-------------------------------------------------
#-------------------------------------------------
لعبة بونغ
# Implementation of classic arcade game Pong
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# ----------------------------------------------------------------
import simplegui
import random
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 10
PAD_HEIGHT = 80
LEFT = False
RIGHT = True
ball_pos = [0, 0]
ball_vel = [0, 0]
paddle1_pos = 0
paddle2_pos = 0
paddle1_vel = 0
paddle2_vel = 0
score1 = 0
score2 = 0
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# helper function
# initialize ball_pos and ball_vel for new ball in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH // 2, HEIGHT // 2]
vx = random.randrange(120, 240) // 60
vy = -random.randrange(60, 180) // 60
if direction == LEFT:
vx = -vx
ball_vel = [vx, vy]
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
# initialize these global variables to their default values
score1 = score2 = 0
paddle1_pos = HEIGHT // 2 - 10
paddle2_pos = HEIGHT // 2 - 10
paddle1_vel = 0
paddle2_vel = 0
spawn_ball(bool(random.randrange(0,2)))
# ----------------------------------------------------------------
def draw(canvas):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 3, "purple") # mid line
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "red") # gutters
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "green")
# draw a circle
canvas.draw_circle([WIDTH / 2, HEIGHT / 2], 85, 4, "Purple")
# update ball
ball_pos[0] = ball_pos[0] + ball_vel[0]
ball_pos[1] = ball_pos[1] + ball_vel[1]
# collision with top or bottom wall (just inverse the vertical velocity]
if (ball_pos[1] - BALL_RADIUS <= 0) or (ball_pos[1] + BALL_RADIUS >= HEIGHT):
ball_vel[1] = -ball_vel[1]
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 13, "Purple")
canvas.draw_circle(ball_pos, BALL_RADIUS, 7, "White")
# update paddle's vertical position, keep paddle on the screen
if not (((paddle1_pos + paddle1_vel) <= 0) or ((paddle1_pos + paddle1_vel + PAD_HEIGHT) >= HEIGHT)):
paddle1_pos = paddle1_pos + paddle1_vel
if not (((paddle2_pos + paddle2_vel) <= 0) or ((paddle2_pos + paddle2_vel + PAD_HEIGHT) >= HEIGHT)):
paddle2_pos = paddle2_pos + paddle2_vel
# draw paddles
canvas.draw_line([0, paddle1_pos],[0, paddle1_pos + PAD_HEIGHT], PAD_WIDTH, "white")
canvas.draw_line([WIDTH, paddle2_pos],[WIDTH, paddle2_pos + PAD_HEIGHT], PAD_WIDTH, "white")
# determine whether paddle and ball collide
if (ball_pos[0] - BALL_RADIUS) <= PAD_WIDTH:
# Ball hit paddle1
if ((ball_pos[1] >= paddle1_pos) and (ball_pos[1] <= (paddle1_pos + PAD_HEIGHT))):
ball_vel[0] = -ball_vel[0]
ball_vel[0] += (ball_vel[0] // 10)
ball_vel[1] += (ball_vel[1] // 10)
else:
score2 += 1
spawn_ball(True)
elif (ball_pos[0] + BALL_RADIUS) >= (WIDTH - PAD_WIDTH):
# Ball hit paddle2
if ((ball_pos[1] >= paddle2_pos) and (ball_pos[1] <= (paddle2_pos + PAD_HEIGHT))):
ball_vel[0] = -ball_vel[0]
ball_vel[0] += (ball_vel[0] // 10)
ball_vel[1] += (ball_vel[1] // 10)
else:
score1 += 1
spawn_ball(False)
# draw score
canvas.draw_text(str(score1), [180, 50], 55, "Red") # left player score
canvas.draw_text(str(score2), [420, 50], 55, "Lime") # right player score
# ----------------------------------------------------------------
def keydown(key):
global paddle1_vel, paddle2_vel
# updating the velocities of paddles
if key == simplegui.KEY_MAP["w"]:
paddle1_vel -= 4
elif key == simplegui.KEY_MAP["s"]:
paddle1_vel += 4
elif key == simplegui.KEY_MAP["up"]:
paddle2_vel -= 4
elif key == simplegui.KEY_MAP["down"]:
paddle2_vel += 4
# ----------------------------------------------------------------
def keyup(key):
global paddle1_vel, paddle2_vel
# making a paddle motionless
if (key == simplegui.KEY_MAP["w"]) or (key == simplegui.KEY_MAP["s"]):
paddle1_vel = 0
elif (key == simplegui.KEY_MAP["up"]) or (key == simplegui.KEY_MAP["down"]):
paddle2_vel = 0
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", new_game, 100)
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# start frame
new_game()
frame.start()
لعبة الذاكرة
# implementation of card game - Memory
import simplegui
import random
# --------------------------------------------------------
# --------------------------------------------------------
# global variables
deck = []
exposed = []
card1 = 0
card2 = 0
state = 0
turns = 0
# --------------------------------------------------------
# --------------------------------------------------------
# helper function to initialize globals
def new_game():
global deck, state, exposed, card1, card2, turns
deck = range(8) + range(8)
random.shuffle(deck)
exposed = [False for x in deck]
state = turns = card1 = card2 = 0
# --------------------------------------------------------
# --------------------------------------------------------
# define event handlers
def mouseclick(pos):
card_num = pos[0] // 50
if (exposed[card_num] != True):
exposed[card_num] = True
global card1, card2, state, turns
if state == 0:
state = 1
card1 = card_num
elif state == 1:
state = 2
card2 = card_num
turns += 1
else:
state = 1
if (deck[card1] != deck[card2]):
exposed[card1] = exposed[card2] = False
card1 = card_num
# --------------------------------------------------------
# cards are logically 50x100 pixels in size
def draw(canvas):
x = 0
i = 0
for num in deck:
if exposed[i] == False:
canvas.draw_line((x, 0), (x, 100), 2, 'yellow')
canvas.draw_line((x, 0), (x+50, 0), 200, 'green')
else:
canvas.draw_text(str(num), [x , 90], 115, "red")
x += 50
i += 1
label.set_text("Turns = " + str(turns))
# --------------------------------------------------------
# --------------------------------------------------------
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(turns))
# --------------------------------------------------------
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# --------------------------------------------------------
# get things rolling
new_game()
frame.start()
# --------------------------------------------------------
# --------------------------------------------------------
لعبة بلاك جاك
# Mini-project #6 - Blackjack
#---------------------------------------------------------------
#---------------------------------------------------------------
#---------------------------------------------------------------
import simplegui
import random
#---------------------------------------------------------------
# load card sprite - 936x384 - source: jfitz.com
CARD_SIZE = (72, 96)
CARD_CENTER = (36, 48)
card_images = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png")
CARD_BACK_SIZE = (72, 96)
CARD_BACK_CENTER = (36, 48)
card_back = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/card_jfitz_back.png")
# initialize some useful global variables
in_play = False
outcome = ""
score = 0
message = ""
display_hole_card = False
game_stop = True
# define globals for cards
SUITS = ('C', 'S', 'H', 'D')
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}
#---------------------------------------------------------------
#---------------------------------------------------------------
# define card class
class Card:
def __init__(self, suit, rank):
if (suit in SUITS) and (rank in RANKS):
self.suit = suit
self.rank = rank
else:
self.suit = None
self.rank = None
print "Invalid card: ", suit, rank
def __str__(self):
return self.suit + self.rank
def get_suit(self):
return self.suit
def get_rank(self):
return self.rank
def draw(self, canvas, pos):
card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank),
CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))
canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)
#---------------------------------------------------------------
# define hand class
class Hand:
def __init__(self):
self.cards_list = []
def __str__(self):
ans = "Hand contains "
for x in self.cards_list:
ans += str(x) + " "
return ans
def add_card(self, card):
self.cards_list.append(card)
def get_value(self):
# count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust
value = 0
has_rank = False
for x in self.cards_list:
r = x.get_rank()
if r == RANKS[0]:
has_rank = True
value += VALUES[r]
if has_rank and (value+10 <= 21):
value += 10
return value
def draw(self, canvas, pos):
for x in self.cards_list:
x.draw(canvas, pos)
pos[0] += 100
#---------------------------------------------------------------
# define deck class
class Deck:
def __init__(self):
self.cards_list = [Card(s,r) for s in SUITS for r in RANKS]
def shuffle(self):
random.shuffle(self.cards_list)
def deal_card(self):
return self.cards_list.pop(-1)
def __str__(self):
ans = "Deck contains "
for x in self.cards_list:
ans += str(x) + " "
return ans
#---------------------------------------------------------------
#---------------------------------------------------------------
#define event handlers for buttons
def deal():
global outcome, in_play, game_deck, player_hand
global dealer_hand, message, display_hole_card, game_stop, score
if game_stop == False:
outcome = "You lose."
score -= 1
message = "New deal?"
display_hole_card = True
game_stop = True
else:
game_deck = Deck()
game_deck.shuffle()
player_hand = Hand()
dealer_hand = Hand()
for i in range(2):
player_hand.add_card( game_deck.deal_card() )
dealer_hand.add_card( game_deck.deal_card() )
in_play = True
display_hole_card = False
outcome = ""
message = "Hit or Stand?"
game_stop = False
#---------------------------------------------------------------
def hit():
global outcome, score, message, display_hole_card, game_stop
if game_stop == False:
# if the hand is in play, hit the player
if in_play:
if player_hand.get_value() <= 21:
player_hand.add_card(game_deck.deal_card())
if player_hand.get_value() > 21:
outcome = "You went bust and lose."
message = "New deal?"
score -= 1
display_hole_card = True
game_stop = True
else:
dealer_hand.add_card(game_deck.deal_card())
#---------------------------------------------------------------
def stand():
global in_play, outcome, score, message, display_hole_card, game_stop
if game_stop == False:
message = "New deal?"
in_play = False
display_hole_card = True
# repeatedly hit dealer until his hand has value 17 or more
while (dealer_hand.get_value() < 17):
hit()
if dealer_hand.get_value () > 21:
outcome = "You won."
score += 1
else:
if player_hand.get_value() <= dealer_hand.get_value():
outcome = "You lose."
score -= 1
else:
outcome = "You won."
score += 1
game_stop = True
#---------------------------------------------------------------
#---------------------------------------------------------------
# draw handler
def draw(canvas):
canvas.draw_text("Blackjack", [100, 100], 50, "Red")
canvas.draw_text("Score: " + str(score), [400, 100], 40, "yellow")
canvas.draw_text("Dealer", [40, 200], 40, "Black")
canvas.draw_text("Player", [40, 400], 40, "Black")
canvas.draw_text(outcome, [250, 200], 35, "Black")
canvas.draw_text(message, [300, 400], 40, "Black")
player_hand.draw(canvas, [50, 440])
dealer_hand.draw(canvas, [50, 230])
if display_hole_card == False:
canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE
, [50 + CARD_CENTER[0], 230 + CARD_CENTER[1]], CARD_BACK_SIZE)
#-----------------------------------------------------------------
#-----------------------------------------------------------------
# initialization frame
frame = simplegui.create_frame("Blackjack", 600, 600)
frame.set_canvas_background("Green")
#-----------------------------------------------------------------
#create buttons and canvas callback
frame.add_button("Deal", deal, 200)
frame.add_button("Hit", hit, 200)
frame.add_button("Stand", stand, 200)
frame.set_draw_handler(draw)
#-----------------------------------------------------------------
# defining global objects
game_deck = Deck()
player_hand = Hand()
dealer_hand = Hand()
#-----------------------------------------------------------------
# get things rolling
deal()
frame.start()
سفينة الفضاء
#--------------------------------------------------------
#--------------------------------------------------------
# miniproject 7 - Spaceship
import simplegui
import math
import random
#--------------------------------------------------------
# helper functions and classes
# class which contains information for an image
class ImageInfo:
def __init__(self, center, size, radius = 0, lifespan = None, animated = False):
self.center = center
self.size = size
self.radius = radius
if lifespan:
self.lifespan = lifespan
else:
self.lifespan = float('inf')
self.animated = animated
def get_center(self):
return self.center
def get_size(self):
return self.size
def get_radius(self):
return self.radius
def get_lifespan(self):
return self.lifespan
def get_animated(self):
return self.animated
#--------------------------------------------------------
#--------------------------------------------------------
# -----------------------------------------------------------------------------
# art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim
# debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png
# debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png
debris_info = ImageInfo([320, 240], [640, 480])
debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")
# nebula images - nebula_brown.png, nebula_blue.png
nebula_info = ImageInfo([400, 300], [800, 600])
nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png")
# splash image
splash_info = ImageInfo([200, 150], [400, 300])
splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png")
# ship image
ship_info = ImageInfo([45, 45], [90, 90], 35)
ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")
# missile image - shot1.png, shot2.png, shot3.png
missile_info = ImageInfo([5,5], [10, 10], 3, 50)
missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png")
# asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png
asteroid_info = ImageInfo([45, 45], [90, 90], 40)
asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")
# animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png
explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")
# sound assets purchased from sounddogs.com, please do not redistribute
soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3")
missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3")
missile_sound.set_volume(.5)
ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3")
explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3")
# alternative upbeat soundtrack by composer and former IIPP student Emiel Stopler
# please do not redistribute without permission from Emiel at http://www.filmcomposer.nl
#soundtrack = simplegui.load_sound("https://storage.googleapis.com/codeskulptor-assets/ricerocks_theme.mp3")
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
#--------------------------------------------------------
# globals for user interface
WIDTH = 800
HEIGHT = 600
score = 0
lives = 3
time = 0
FRICTION_CONSTANT = 0.05
#---------------------------------------------------------
# helper functions to handle transformations
def angle_to_vector(ang):
return [math.cos(ang), math.sin(ang)]
def dist(p,q):
return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2)
# -----------------------------------------------------------------------------
# Ship class
class Ship:
def __init__(self, pos, vel, angle, image, info):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.thrust = False
self.angle = angle
self.angle_vel = 0
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
def draw(self,canvas):
if self.thrust:
canvas.draw_image(self.image, [self.image_center[0]+90, self.image_center[1]],
self.image_size, self.pos, self.image_size, self.angle)
ship_thrust_sound.play()
else:
canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle)
ship_thrust_sound.rewind()
# motion control scheme for the spaceship
def update(self):
self.angle += self.angle_vel
self.pos[0] += self.vel[0]
self.pos[1] += self.vel[1]
self.pos[0] %= WIDTH
self.pos[1] %= HEIGHT
self.vel[0] *= (1-FRICTION_CONSTANT)
self.vel[1] *= (1-FRICTION_CONSTANT)
if self.thrust:
forward_thrust = angle_to_vector(self.angle)
self.vel[0] += (forward_thrust[0])/2
self.vel[1] += (forward_thrust[1])/2
def shoot(self):
global a_missile
forward_vector = angle_to_vector(self.angle)
missile_pos = [0,0]
missile_pos[0] = self.pos[0] + self.radius * forward_vector[0]
missile_pos[1] = self.pos[1] + self.radius * forward_vector[1]
missile_vel = [0, 0]
missile_vel[0] = self.vel[0] + (forward_vector[0]*5)
missile_vel[1] = self.vel[1] + (forward_vector[1]*5)
a_missile = Sprite(missile_pos, missile_vel, 0, 0, missile_image, missile_info, missile_sound)
# -----------------------------------------------------------------------------
# Sprite class
class Sprite:
def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.angle = ang
self.angle_vel = ang_vel
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
self.lifespan = info.get_lifespan()
self.animated = info.get_animated()
self.age = 0
if sound:
sound.rewind()
sound.play()
def draw(self, canvas):
canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle)
def update(self):
self.angle += self.angle_vel
self.pos[0] += self.vel[0]
self.pos[1] += self.vel[1]
self.pos[0] %= WIDTH
self.pos[1] %= HEIGHT
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# event handlers
def draw(canvas):
global time
# animiate background
time += 1
wtime = (time / 4) % WIDTH
center = debris_info.get_center()
size = debris_info.get_size()
canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT])
canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
# draw ship and sprites
my_ship.draw(canvas)
a_rock.draw(canvas)
a_missile.draw(canvas)
# update ship and sprites
my_ship.update()
a_rock.update()
a_missile.update()
# draw lives and score
canvas.draw_text("Lives: " + str(lives), [WIDTH - 120, 40], 30, "white")
canvas.draw_text("Score: " + str(score), [WIDTH - 120, 80], 30, "white")
# -----------------------------------------------------------------------------
# key handlers
def keydown(key):
if key == simplegui.KEY_MAP["left"]:
my_ship.angle_vel = -0.1
elif key == simplegui.KEY_MAP["right"]:
my_ship.angle_vel = 0.1
elif key == simplegui.KEY_MAP["up"]:
my_ship.thrust = True
elif key == simplegui.KEY_MAP["space"]:
my_ship.shoot()
def keyup(key):
if (key == simplegui.KEY_MAP["left"]) or (key == simplegui.KEY_MAP["right"]):
my_ship.angle_vel = 0
elif key == simplegui.KEY_MAP["up"]:
my_ship.thrust = False
# -----------------------------------------------------------------------------
# timer handler that spawns a rock
def rock_spawner():
global a_rock
width = random.randrange(WIDTH)
height = random.randrange(HEIGHT)
vel = [0, 0]
vel[0] = random.randrange(2)
vel[1] = random.randrange(2)
ang = random.random()
ang_vel = random.random() - 0.5
a_rock = Sprite([width, height], vel, ang, ang_vel, asteroid_image, asteroid_info)
# -----------------------------------------------------------------------------
# initialize frame
frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT)
# -----------------------------------------------------------------------------
# initialize ship and two sprites
my_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info)
a_rock = Sprite([WIDTH / 3, HEIGHT / 3], [1, 1], 0, 0, asteroid_image, asteroid_info)
a_missile = Sprite([2 * WIDTH / 3, 2 * HEIGHT / 3], [-1,1], 0, 0, missile_image, missile_info, missile_sound)
# -----------------------------------------------------------------------------
# register handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
timer = simplegui.create_timer(1000.0, rock_spawner)
# -----------------------------------------------------------------------------
# get things rolling
timer.start()
frame.start()
لعبة الكويكبات
#-------------------------------------------------------------------
# implementation of Spaceship - program template for RiceRocks
import simplegui
import math
import random
#-------------------------------------------------------------------
# helper classes
class ImageInfo:
def __init__(self, center, size, radius = 0, lifespan = None, animated = False):
self.center = center
self.size = size
self.radius = radius
if lifespan:
self.lifespan = lifespan
else:
self.lifespan = float('inf')
self.animated = animated
def get_center(self):
return self.center
def get_size(self):
return self.size
def get_radius(self):
return self.radius
def get_lifespan(self):
return self.lifespan
def get_animated(self):
return self.animated
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim
# debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png
# debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png
debris_info = ImageInfo([320, 240], [640, 480])
debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")
# nebula images - nebula_brown.png, nebula_blue.png
nebula_info = ImageInfo([400, 300], [800, 600])
nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png")
# splash image
splash_info = ImageInfo([200, 150], [400, 300])
splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png")
# ship image
ship_info = ImageInfo([45, 45], [90, 90], 35)
ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")
# missile image - shot1.png, shot2.png, shot3.png
missile_info = ImageInfo([5,5], [10, 10], 3, 50)
missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png")
# asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png
asteroid_info = ImageInfo([45, 45], [90, 90], 40)
asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")
# animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png
explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")
# sound assets purchased from sounddogs.com, please do not redistribute
# .ogg versions of sounds are also available, just replace .mp3 by .ogg
soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3")
missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3")
ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3")
explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3")
# alternative upbeat soundtrack by composer and former IIPP student Emiel Stopler
# please do not redistribute without permission from Emiel at http://www.filmcomposer.nl
#soundtrack = simplegui.load_sound("https://storage.googleapis.com/codeskulptor-assets/ricerocks_theme.mp3")
#-------------------------------------------------------------------
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# globals for user interface
WIDTH = 800
HEIGHT = 600
score = 0
lives = 3
time = 0
started = False
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# helper functions to handle transformations
def angle_to_vector(ang):
return [math.cos(ang), math.sin(ang)]
def dist(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
def process_sprite_group(s_group, canvas):
for x in set(s_group):
x.draw(canvas)
if x.update():
s_group.remove(x)
def group_collide(s_group, other_object):
has_collide = False
for x in set(s_group):
if (x.collide(other_object)):
a_explosion = Sprite(x.get_position(), [0, 0], 0, 0, explosion_image, explosion_info, explosion_sound)
explosion_group.add(a_explosion)
s_group.remove(x)
has_collide = True
return has_collide
def group_group_collide(group1, group2):
total_collisions = 0
for x in set(group1):
if group_collide(group2, x):
group1.discard(x)
total_collisions += 1
return total_collisions
#-------------------------------------------------------------------
# Ship class
class Ship:
def __init__(self, pos, vel, angle, image, info):
self.pos = [pos[0], pos[1]]
self.vel = [vel[0], vel[1]]
self.thrust = False
self.angle = angle
self.angle_vel = 0
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
def get_position(self):
return self.pos
def get_radius(self):
return self.radius
def draw(self,canvas):
if self.thrust:
canvas.draw_image(self.image, [self.image_center[0] + self.image_size[0], self.image_center[1]] , self.image_size,
self.pos, self.image_size, self.angle)
else:
canvas.draw_image(self.image, self.image_center, self.image_size,
self.pos, self.image_size, self.angle)
def update(self):
# update angle
self.angle += self.angle_vel
# update position
self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH
self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT
# update velocity
if self.thrust:
acc = angle_to_vector(self.angle)
self.vel[0] += acc[0] * .1
self.vel[1] += acc[1] * .1
self.vel[0] *= .99
self.vel[1] *= .99
def set_thrust(self, on):
self.thrust = on
if on:
ship_thrust_sound.rewind()
ship_thrust_sound.play()
else:
ship_thrust_sound.pause()
def increment_angle_vel(self):
self.angle_vel += .05
def decrement_angle_vel(self):
self.angle_vel -= .05
def shoot(self):
forward = angle_to_vector(self.angle)
missile_pos = [self.pos[0] + self.radius * forward[0], self.pos[1] + self.radius * forward[1]]
missile_vel = [self.vel[0] + 6 * forward[0], self.vel[1] + 6 * forward[1]]
a_missile = Sprite(missile_pos, missile_vel, self.angle, 0, missile_image, missile_info, missile_sound)
missile_group.add(a_missile)
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# Sprite class
class Sprite:
def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.angle = ang
self.angle_vel = ang_vel
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
self.lifespan = info.get_lifespan()
self.animated = info.get_animated()
self.age = 0
if sound:
sound.rewind()
sound.play()
def get_position(self):
return self.pos
def get_radius(self):
return self.radius
def draw(self, canvas):
if self.animated:
canvas.draw_image(self.image, [self.image_center[0] + self.age*self.image_size[0] ,self.image_center[1]] , self.image_size,
self.pos, self.image_size, self.angle)
else:
canvas.draw_image(self.image, self.image_center, self.image_size,
self.pos, self.image_size, self.angle)
def update(self):
# update angle
self.angle += self.angle_vel
# update position
self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH
self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT
self.age += 1
return (self.age >= self.lifespan)
def collide(self,other_object):
return ( dist(self.get_position(), other_object.get_position()) <= (self.radius + other_object.radius) )
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# key handlers to control ship
def keydown(key):
if key == simplegui.KEY_MAP['left']:
my_ship.decrement_angle_vel()
elif key == simplegui.KEY_MAP['right']:
my_ship.increment_angle_vel()
elif key == simplegui.KEY_MAP['up']:
my_ship.set_thrust(True)
elif key == simplegui.KEY_MAP['space']:
my_ship.shoot()
def keyup(key):
if key == simplegui.KEY_MAP['left']:
my_ship.increment_angle_vel()
elif key == simplegui.KEY_MAP['right']:
my_ship.decrement_angle_vel()
elif key == simplegui.KEY_MAP['up']:
my_ship.set_thrust(False)
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# mouseclick handlers that reset UI and conditions whether splash image is drawn
def click(pos):
global started, lives, score
center = [WIDTH / 2, HEIGHT / 2]
size = splash_info.get_size()
inwidth = (center[0] - size[0] / 2) < pos[0] < (center[0] + size[0] / 2)
inheight = (center[1] - size[1] / 2) < pos[1] < (center[1] + size[1] / 2)
if (not started) and inwidth and inheight:
started = True
lives = 3
score = 0
soundtrack.rewind()
soundtrack.play()
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def draw(canvas):
global time, started, lives, score, rock_group
# animiate background
time += 1
wtime = (time / 4) % WIDTH
center = debris_info.get_center()
size = debris_info.get_size()
canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT])
canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
# draw UI
canvas.draw_text("Lives", [50, 50], 22, "White")
canvas.draw_text("Score", [680, 50], 22, "White")
canvas.draw_text(str(lives), [50, 80], 22, "White")
canvas.draw_text(str(score), [680, 80], 22, "White")
# draw and update ship and sprites
my_ship.draw(canvas)
my_ship.update()
process_sprite_group(rock_group,canvas)
process_sprite_group(missile_group,canvas)
process_sprite_group(explosion_group,canvas)
# update lives
if group_collide(rock_group, my_ship):
lives -= 1
# update score
score += group_group_collide(rock_group, missile_group)
if lives == 0:
started = False
rock_group = set()
# draw splash screen if not started
if not started:
canvas.draw_image(splash_image, splash_info.get_center(),
splash_info.get_size(), [WIDTH / 2, HEIGHT / 2],
splash_info.get_size())
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# timer handler that spawns a rock
def rock_spawner():
if started:
if len(rock_group) != 12:
rock_pos = [random.randrange(0, WIDTH), random.randrange(0, HEIGHT)]
if not (dist(my_ship.get_position(), rock_pos) <= 10):
rock_vel = [(random.random() * .6 - .3) + score/5.0 , (random.random() * .6 - .3) + score/5.0]
rock_avel = random.random() * .2 - .1
a_rock = Sprite(rock_pos, rock_vel, 0, rock_avel, asteroid_image, asteroid_info)
rock_group.add(a_rock)
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# initialize stuff
frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT)
#-------------------------------------------------------------------
# initialize ship and two sprites
my_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info)
rock_group = set([])
missile_group = set([])
explosion_group = set([])
#-------------------------------------------------------------------
# register handlers
frame.set_keyup_handler(keyup)
frame.set_keydown_handler(keydown)
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
#-------------------------------------------------------------------
timer = simplegui.create_timer(1000.0, rock_spawner)
#-------------------------------------------------------------------
# get things rolling
timer.start()
frame.start()
تحميل الأكواد بملف واحد
تستطيع تحميل ملفات الأكواد كاملة مره واحده بدلاً من نسخ ولصق الأكواد في الأعلى ان كنت تريد تحميلهم وقراءة اعمق لطريقة عمل الأكواد