Learn the Basics of Kotlin ~~ep1~
An Absolute Beginner’s Guide to Kotlinを進めた
Variables 変数
可変
varキーワードを使用する。型指定(type引数)は省略できる。
var greeting: String = “Hello World!”
var greeting = “Hello World!”
不変
valキーワードを使用する
val greeting = “Hello Kotlin”
文字列:String型
文字列の連結 +演算子を使用する
val language = "Kotlin"
val creator = "JetBrains"
val description = language + " is created by " + creator
変数の前に$を付けると二重引用符で囲まれた変数を使用できる。
val releaseDate = “20110701”
val releaseString = “Kotlinは$releaseDateでリリースされました”
数字
主な数値タイプ
int 整数 32bit
long 整数 64bit
float 浮動小数点 32bit
double 浮動小数点 64bit
val num1 = 42 //int
val num2 = 3.14 //double
val num3 = 42L //long
val num4 = 3.14f //float
toType関数を使用して型変換が可能
val num1 = 42.toFloat() //float
val num2 = num1.toDouble() //double
アンダースコアをもちいて数値を読みやすくできる
val distToMoon = 92_960_000 //miles(inferred type int)
booleans
true or false. 他と変わらん
Nullability(Null安全):まだよくわからん
null:何とも等しくない。Nullを原則許容しない仕組みのことを指す。
Null安全についての記事:【Null安全】Kotlin Java比較メモ 正しいNull安全の使い方
val x: Int // Error - variable must be initialized
val x: Int = null // Error - null cannot be a value for non-null type Int
val x: Int? = null // OK
val y: String = null // Error - null cannot be a value for non-null type String
val y: String? = null // OK
Null値の処理に役立つ演算子
nullの長さを返そうとしてエラー
val name: String? = null
println(name.length) // Error - Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
?を用いるとnullを返すからOK
val name: String? = null
println(name?.length) // prints “null”
null許容変数をnullにできないことが確実に分かっている場合は!!を使用する
var name: String? = null
name = "Treehouse"
println(name!!.length) // prints "9"
Collections
配列 リスト マップ
Arrays 配列
arrayOf関数を使用する
val cardNames: Array = arrayOf(“Jack”, “Queen”, “King”)
val cardNames = arrayOf(“Jack”, “Queen”, “King”) //型指定の省略cardNames[0] = “Ace”
配列は固定サイズなため、追加・削除する方法はない。
コレクションのアイテムを追加・削除したい場合はlistを使用する。
list リスト
listとmutablelistがある
list:ほぼarray
mutablelist:アイテムの変更・追加・削除が可能。mutableListOf関数を使用
val cards = mutableListOf(“Jack”, “Queen”, “King)
mutableListのオプション
cards.add(“Ace”)
cards.remove(“Jack”)
cards.clear() //empty list
card.addAll(“Jack”, “Queen”, “King”)
maps マップ
mapとmultableMapがある。これはlistと同じ感じ。
キーと値のペアを保存
val cards = mapOf(“Jack” to 11, “Queen” to 12, “King” to 13)
val jackValue = cards[“Jack”] // 11
値を追加したい場合など
val cards = mutableMapOf(“Jack” to 11, “Queen” to 12, “King” to 13)
cards[“Ace”] = 1
toMutableMap関数を使用して、マップをMutableMapに変換することもできる。
val cards = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val mutableCards = cards.toMutableMap()
Control Flow
Looping ループ処理 forループ whileループがある
for文
foreach文 配列を表示
for (card in cards) {
println(card)
}
例 i = 1から10
for(i in 1..10){
println(i)
}
例 i = 10から1 downTo演算子を用いる
for(i in 10 downTo 1){
println(i)
}
mapを表示
val cards = mapOf(“Jack” to 11, “Queen” to 12, “King” to 13)
for ((name, value) in cards){
println(“$name, $value”)
}
while文 他と同じで!falseの間はループ
while (stillDownloading) {
println(“Downloading…”)
}
if Expression if文
基本的には他と似てる
if文を使用した変数の定義。1行のみの場合は{}は省略可能
val aIsBigger = if (a > b){ true } else { false }
val aIsBigger = if (a > b) true else false
When Expression
switch的なやつらしい。kotlinではswitch文じゃなくてwhenを使う。
when (cardInt) {
11 -> println(“jack”)
12 -> println(“queen”)
13 -> println(“king”)
}
if文と同様に変数の定義にも使える。else必須
val cardName = when (cardInt) {
11 -> println(“jack”)
12 -> println(“queen”)
13 -> println(“king”)
else -> “Other”
}
Functions 関数
funキーワードを用いる。楽しそう。
fun printJack(){
println(“Jack”)
}
引数あり
fun printCard(cardName: String, cardValue: Int){
println(“$cardName = $cardValue”)
}
返り値あり
fun getCardString(cardName: String, cardValue: Int): String{
return (“$cardName = $cardValue”)
}
中身がreturnのみの場合は省略して駆ける。返り値の型指定も省略できる。
fun getCardString(cardName: String, cardValue: Int): String = “$cardName = $cardValue”
fun getCardString(cardName: String, cardValue: Int) = "$cardName = $cardValue"
参考サイト:An Absolute Beginner’s Guide to Kotlin
0 notes
MemoryGame.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Project1
{
class MemoryGame
{
// Attributes
private int numGuesses; // hold the number of guesses someone has made
private Stopwatch sw; // used to start/stop/reset and get how long the game has been running
private int currentClickCount; // used to figure out what part in the 2 card click cycle you are at
private string[,] cardValues; // 2-dimentional (4 row x 8 column) array to hold the text values we are matching
private int numRows; // variable to use instead of (4)
private int numColumns; // variable to use instead of (8)
private int numMatches; // our match count - in a game with 32 cards when you hit 16 matches you are done
private int[] pickOne; // array to hold the row + column value of the first card
private int[] pickTwo; // array to hold the row + column value of the second card
// Constructor
public MemoryGame(int nR, int nC)
{
// set the numRows and numColums variables
// give some memory to our pickOne and pickTwo arrays
// give some memory to our cardvalues array
// give some memory to our stopwatch instance
// Initialize everything
resetGame();
}
// Create Properties for:
//------------------------
// CurrentClickCount
// NumGuesses
// NumRows
// NumColumns
// PickOne
// PickTwo
// Create a function that starts the stopwatch
public void StartTime()
{
}
// Create a function that retrieves the stopwatch's current value
public decimal GetTime()
{
}
// Create a function that returns the value of the card
public string GetCardValue(int r, int c)
{
}
// checks the card values of the two picks, returns true if they are the same, false otherwise
public bool matchMade()
{
}
// similar to matchMade() - this checks the card values of the two picks and increases the numMatches count if they are the same
// also returns true/false if the game is finished or not
public bool GameWon()
{
}
// reset the game back to it's default states
public void resetGame()
{
// initialize guesses
// reset the picks to an invalid value
// create a random object to generate a random number
Random r = new Random();
// create a list of characters to choose from for our match game
string allChoices = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "!@#$%^*()";
// create an array of characters to hold all of the needed cards
char[] guessPool;
// give guessPool some memory
// create a temporary character to hold the current selection
// generate all 32 characters (16 pairs of characters)
// Get one random character and then place it in the next slot too
// Ex: if we are looking to fill 32 cards then we need 16 random character
// we don't want any duplicates so keep trying to find a character that hasn't been picked before
// HINT: look to use something like Array.IndexOf
// Once you find an unused character double it up
// Take the array we have and randomize the letters in it
// HINT - call the ShuffleStuff function below
// assign our cardValues array values from our now valid list of characters (guessPool)
// reset the stopwatch
}
// Utility function to shuffle cards
public static void ShuffleStuff(char[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(i, array.Length); // Don't select from the entire array on subsequent loops
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
0 notes